Word Ladder II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
Return an empty list if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20): The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Solution
public class Solution {
private HashMap<String, Integer> map;
private void dfs(String word, String end, List<String> sequence, List<List<String>> res){
if(map.get(word) == map.get(end) && !end.equals(word)) return;
else if(end.equals(word)){
List<String> list = new LinkedList<String>(sequence);
list.add(word);
Collections.reverse(list);
res.add(list);
return;
}
sequence.add(word);
for(int i=0; i<word.length(); i++){
char[] wordArray = word.toCharArray();
for(char ch = 'a'; ch <= 'z'; ch++){
if(wordArray[i] == ch) continue;
wordArray[i] = ch;
String tmp = new String(wordArray);
if(map.containsKey(tmp) && map.get(tmp) == (map.get(word) - 1))
dfs(tmp, end, sequence, res);
}
}
sequence.remove(word);
}
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> res = new ArrayList<List<String>>();
LinkedList<String> queue = new LinkedList<String>();
map = new HashMap<String, Integer>();
queue.add(start);
map.put(start, 1);
if(start.equals(end)){
res.add(queue);
return res;
}
while(!queue.isEmpty()){
String word = queue.poll();
for(int i=0; i<word.length(); i++){
char[] wordArray = word.toCharArray();
for(char j='a'; j<='z'; j++){
if(wordArray[i] == j)
continue;
wordArray[i] = j;
String tmp = new String(wordArray);
if(tmp.endsWith(end)){
map.put(tmp, map.get(word)+1);
i = word.length();
queue.clear();
break;
}
if(dict.contains(tmp) && !map.containsKey(tmp)){
map.put(tmp, map.get(word) + 1);
queue.add(tmp);
}
}
}
}
if(map.containsKey(end))
dfs(end, start, new LinkedList<String>(), res);
return res;
}
}