126. Word Ladder II
Word Ladder II
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;
}
}Last updated