127.Word Ladder
1-Queue + Set
https://leetcode.com/problems/word-ladder/discuss/40707/Easy-76ms-C++-Solution-using-BFS
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet<>(wordList);
Set<String> visited = new HashSet<>();
Deque<String> queue = new ArrayDeque<>();
queue.offerLast(beginWord);
for(int len = 1; !queue.isEmpty(); len++){
for(int i = queue.size(); i > 0; i--){
String cur = queue.pollFirst();
if(cur.equals(endWord))
return len;
for(int j = 0; j < cur.length(); j++){
char[] ch = cur.toCharArray();
for(char c = 'a'; c <= 'z'; c++){
if(c == cur.charAt(j))
continue;
ch[j] = c;
String newString = new String(ch);
if(dict.contains(newString) && visited.add(newString))
queue.offerLast(newString);
}
}
}
}
return 0;
}
}