大致框架:用bfs,从start开始,建一个图,parent node连接着可以变到的node (aka. in dict || ==end)
与word ladder 区别:
1. 没有了global value ===> 每个node 包含了对应的lvl
2. 两个queue变成一个queue ===> node里有对应的lvl 不再需要两个queue
3. HashSet visited 变成graph ===> graph保存更多信息(lvl, parent nodes)
新点: graph的构建:自建一个class Node来保存自己需要的信息,edge已list的形式保存, 用HashMap来保存所有的node。
具体实现:
新建一个class Node { String s, int level, List<Node> pre} 来保存这个node的string和parent node (相当于adjacency list)
用bfs构建一个存这个Node的graph: HashMap<String, Node>, 一边构建一边查:
prev = dequeue queue
prev的每个oneEditWord:
0. string.equals(end): 用dfs从end开始往上traverse, 加入res。
1. 新string: 新建node, 加prev, 放进map,放进queue
2. string已存在: 如果string对应的node的level是prev.level+1 (代表是最新一层建出来的),就把这个prev加到node的prev list里面
需要注意的细节:
1. end要么加进dict要么在if里加上改成if (dict.contains(newItem)||newItem.equals(end)) 来include最后的case
2. 当map里已有newItem时不要重复加到queue里
3. dfs里add&remove都是在0;
//4:11
public class Solution {
class Node {
String s;
int l;
List<Node> prev;
public Node (String str, int lvl) {
s = str;
l = lvl;
prev = new ArrayList<Node>();
}
public void addPrev(Node pre) {
prev.add(pre);
}
}
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> res = new ArrayList<List<String>>();
if (start==null||end==null||start.length()!=end.length()) return res;
HashMap<String, Node> map = new HashMap<String, Node>();
Queue<String> queue = new LinkedList<String>();
Node sn = new Node(start, 1);
dict.add(end);
map.put(start, sn);
queue.add(start);
while (!queue.isEmpty()) {
String cur = queue.remove();
Node prevNode = map.get(cur);
if (cur.equals(end)) {
dfs(map.get(end), map, new ArrayList<String>(), res);
return res;
}
for (int i=0;i<cur.length();i++) {
char[] arr = cur.toCharArray();
for (char c='a';c<='z';c++) {
if (c==cur.charAt(i)) continue;
arr[i]=c;
String newItem = new String(arr);
if (dict.contains(newItem)) {
if (!map.containsKey(newItem)) {
Node n = new Node(newItem, prevNode.l + 1);
map.put(newItem, n);
n.addPrev(prevNode);
queue.add(newItem);
} else {
Node node = map.get(newItem);
if (node.l==prevNode.l+1) {
node.addPrev(prevNode);
}
}
}
}
}
}
return res;
}
private void dfs(Node end, Map<String, Node> map,
List<String> curPath, List<List<String>> paths) {
curPath.add(0, end.s);
if (end.prev.isEmpty()) {
paths.add(new ArrayList<String>(curPath));
} else {
for (Node pre: end.prev) {
dfs(pre, map, curPath, paths);
}
}
curPath.remove(0);
}
}