关注
public class Solution {
public List<List<String>> findLadders(String start, String end, List<String> words) {
/**
核心思路是倒序拍 end--> list of word can to end
to end word --> list of word to this word
...
to begin
*/
Set<String> dict = new HashSet<>(words);
List<List<String>> res = new ArrayList<List<String>>();
if(start.compareTo(end) == 0) return res;
Set<String> visited = new HashSet<String>();
Set<String> cur = new HashSet<String>();
HashMap<String, ArrayList<String>> graph = new HashMap<String, ArrayList<String>>();
graph.put(end,new ArrayList<String>());
cur.add(start);
boolean found = false;
while (!cur.isEmpty() && found == false) {
Set<String> queue = new HashSet<String>(); //next level queue
for(String word : cur) {
visited.add(word);
}
for(String str : cur) {
char[] word = str.toCharArray();
for (int j = 0; j < word.length; ++j) {
char before = word[j];
for (char ch = 'a'; ch <= 'z'; ++ch) {
if (ch == before) continue;
word[j] = ch;
String temp = new String(word);
if (!dict.contains(temp)) continue;
if (found == true && end.compareTo(temp) != 0) continue; //not the shortest path
if (end.compareTo(temp) == 0) {
found = true;
(graph.get(end)).add(str);
continue;
}
if (!visited.contains(temp)) {
queue.add(temp);
if (!graph.containsKey(temp)) {
ArrayList<String> l = new ArrayList<String>();
l.add(str);
graph.put(temp,l);
} else {
(graph.get(temp)).add(str);
}
}
}
word[j] = before;
}
}
cur = queue;
}
if (found == true) {
ArrayList<String> path = new ArrayList<String>();
trace(res, graph, path, start, end);
}
return res;
}
public void trace(List<List<String>> res, HashMap<String,
ArrayList<String>> graph, ArrayList<String> path, String start, String now) {
path.add(now);
if (now.compareTo(start) == 0) {
ArrayList<String> ans = new ArrayList<String>(path);
Collections.reverse(ans);
res.add(ans);
path.remove(path.size() - 1);
return;
}
ArrayList<String> cur = graph.get(now);
for (int i = 0; i < cur.size(); ++i) {
trace(res,graph,path,start,cur.get(i));
}
path.remove(path.size()-1);
}
}
查看原帖
点赞 评论
相关推荐
牛客热帖
更多
正在热议
更多
# 对2025年忏悔 #
1930次浏览 50人参与
# 腾讯音乐求职进展汇总 #
145333次浏览 1038人参与
# 实习没人带,苟住还是跑路? #
7500次浏览 166人参与
# 我们是不是被“优绩主义”绑架了? #
7131次浏览 247人参与
# 元旦假期你打算怎么过 #
5234次浏览 132人参与
# 大家实习都在做什么? #
6561次浏览 63人参与
# 电网笔面经互助 #
56809次浏览 470人参与
# 春招前还要继续实习吗? #
1804次浏览 27人参与
# 面试官问过你最刁钻的问题是什么? #
4979次浏览 66人参与
# 一人说一家双休的公司 #
4182次浏览 69人参与
# 毕业论文怎么查AI率 #
70143次浏览 1941人参与
# 运营来爆料 #
72254次浏览 452人参与
# 非技术2024笔面经 #
451377次浏览 4918人参与
# 参加过提前批的机械人,你们还参加秋招么 #
105510次浏览 1649人参与
# 牛客2025仙途报告 #
31261次浏览 397人参与
# 你做过哪些dirty work #
25093次浏览 155人参与
# 联影求职进展汇总 #
165148次浏览 832人参与
# 你们的毕业论文什么进度了 #
1224028次浏览 9903人参与
# 硬件人秋招进展 #
262634次浏览 3963人参与
# 晒一晒你收到的礼盒 #
93244次浏览 446人参与
查看2道真题和解析
