BFS 搜索, unweighted graph
Time complexity = O(n*26^l), l = len(word), n=wordList.size()
Space complexity = O(n)
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (wordList == null || wordList.size() == 0) {
return 0;
}
Set<String> wordSet = new HashSet<>();
for (String word : wordList) {
wordSet.add(word);
}
if (!wordList.contains(endWord)) {
return 0;
}
if (wordList.contains(beginWord)) {
wordList.remove(beginWord);
}
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
int count = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
char[] charArray = word.toCharArray();
for (int j = 0; j < beginWord.length(); j++) {
char cur = charArray[j];
for (char c = 'a'; c <= 'z'; c++) {
if (c == charArray[j]) {
continue;
}
charArray[j] = c;
String newWord = new String(charArray);
if (newWord.equals(endWord)) {
return count + 1;
}
if (wordSet.contains(newWord)) { // here is important
queue.offer(newWord);
wordSet.remove(newWord); // this step is important
}
charArray[j] = cur;
}
}
}
count ++;
}
return 0;
}
}