File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+
3+ private String [] words ;
4+ private boolean [] visited ;
5+ private String target ;
6+ private int answer ;
7+
8+ public int solution (String begin , String _target , String [] _words ) {
9+ words = _words ;
10+ target = _target ;
11+ visited = new boolean [words .length ];
12+ answer = Integer .MAX_VALUE ;
13+ dfs (begin , 0 , 0 );
14+ return (answer == Integer .MAX_VALUE ) ? 0 : answer ;
15+ }
16+
17+ public void dfs (String now , int step , int count ) {
18+ if (now .equals (target )) {
19+ answer = Math .min (answer , count );
20+ return ;
21+ }
22+ if (step == words .length ) {
23+ return ;
24+ }
25+
26+ for (int i =0 ; i <words .length ; i ++) {
27+ if (!visited [i ] && check (now , words [i ])) {
28+ visited [i ] = true ;
29+ dfs (words [i ], step +1 , count +1 );
30+ visited [i ] = false ;
31+ }
32+ }
33+ }
34+
35+ public boolean check (String s1 , String s2 ) {
36+ int count = 0 ;
37+ int len = s1 .length ();
38+ for (int i =0 ; i <len ; i ++) {
39+ count += (s1 .charAt (i ) == s2 .charAt (i )) ? 1 : 0 ;
40+ }
41+ return (count == len -1 );
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments