Word Ladder II
Source
iven two words (start and end), and a dictionary, find all
shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note
All words have the same length.
All words contain only lowercase alphabetic characters.
Java
public class Solution {
public List<List<String>> findLadders(String start, String end,
Set<String> dict) {
List<List<String>> ladders = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
Map<String, Integer> distance = new HashMap<String, Integer>();
dict.add(start);
dict.add(end);
bfs(map, distance, start, end, dict);
List<String> path = new ArrayList<String>();
dfs(ladders, path, start, end, distance, map);
return ladders;
}
void dfs(List<List<String>> ladders, List<String> path, String start,
String end, Map<String, Integer> distance,
Map<String, List<String>> map) {
path.add(start);
if (start.equals(end)) {
ladders.add(new ArrayList<String>(path));
} else {
for (String next : map.get(start)) {
if (distance.containsKey(next) && distance.get(start)+1 == distance.get(next)) {
dfs(ladders, path, next, end, distance, map);
}
}
}
path.remove(path.size() - 1);
}
void bfs(Map<String, List<String>> map, Map<String, Integer> distance,
String start, String end, Set<String> dict) {
Queue<String> q = new LinkedList<String>();
q.offer(start);
distance.put(start, 0);
for (String s : dict) {
map.put(s, new ArrayList<String>());
}
while (!q.isEmpty()) {
String crt = q.poll();
List<String> nextList = expand(crt, dict);
for (String next : nextList) {
map.get(crt).add(next);
if (!distance.containsKey(next)) {
distance.put(next, distance.get(crt) + 1);
q.offer(next);
}
}
}
}
List<String> expand(String crt, Set<String> dict) {
List<String> expansion = new ArrayList<String>();
for (int i = 0; i < crt.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
if (ch != crt.charAt(i)) {
String expanded = crt.substring(0, i) + ch
+ crt.substring(i + 1);
if (dict.contains(expanded)) {
expansion.add(expanded);
}
}
}
}
return expansion;
}
}