@@ -41,8 +41,12 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
41
41
Set <String > startSet = new HashSet <>();
42
42
Set <String > endSet = new HashSet <>();
43
43
Set <String > visited = new HashSet <>();
44
+
44
45
startSet .add (beginWord );
45
- if (dict .contains (endWord )) endSet .add (endWord ); // all transformed words must be in dict (including endWord)
46
+ if (dict .contains (endWord )) {
47
+ endSet .add (endWord ); // all transformed words must be in dict (including endWord)
48
+ }
49
+
46
50
for (int len = 2 ; !startSet .isEmpty (); len ++) {
47
51
Set <String > nq = new HashSet <>();
48
52
for (String w : startSet ) {
@@ -52,11 +56,16 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
52
56
if (c == w .charAt (j )) continue ; // beginWord and endWord should not be the same
53
57
ch [j ] = c ;
54
58
String nb = String .valueOf (ch );
55
- if (endSet .contains (nb )) return len ; // meet from two ends
56
- if (dict .contains (nb ) && visited .add (nb )) nq .add (nb ); // not meet yet, visited is safe to use
59
+ if (endSet .contains (nb )) {
60
+ return len ; // meet from two ends
61
+ }
62
+ if (dict .contains (nb ) && visited .add (nb )) {
63
+ nq .add (nb ); // not meet yet, visited is safe to use
64
+ }
57
65
}
58
66
}
59
67
}
68
+
60
69
startSet = (nq .size () < endSet .size ()) ? nq : endSet ; // switch to small one to traverse from other end
61
70
endSet = (startSet == nq ) ? endSet : nq ;
62
71
}
0 commit comments