Word Ladder
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if(!wordList.contains(endWord)){
return 0;
}
Queue<String> queue = new LinkedList<>();
Set<String> set = new HashSet<>();
queue.offer(beginWord);
set.add(beginWord);
int count = 0;
while(!queue.isEmpty()){
int size = queue.size();
count++;
for(int i = 0; i < size;i++){
String word = queue.poll();
if(word.equals(endWord))
return count;
List<String> nextWords = getNextWordsList(wordList,word);
for(String nw : nextWords){
if(nw == endWord){
return count+1;
}
if(!set.contains(nw)){
set.add(nw);
queue.offer(nw);
}
}
}
}
return 0;
}
public List<String> getNextWordsList(List<String> wordList, String word){
List<String> res = new ArrayList<>();
for(String w : wordList){
int diff = 0;
for(int i = 0; i < w.length();i++){
if(w.charAt(i) != word.charAt(i))
diff++;
}
if(diff == 1){
res.add(w);
}
}
wordList.removeAll(res);
return res;
}
}Last updated