LeetCode 0126 Word Ladder II
作者:互联网
1. 题目描述
2. Solution 1
1、思路分析
本题要求的是最短转换序列,看到最短首先想到的是广度优先搜索。但是本题没有给出显式的图结构,根据单词转换规则:把每个单词都抽象为一个顶点,如果两个单词可以只改变一个字母进行转换,那么说明他们之间有一条双向边。因此只需要把满足转换条件的点相连。由示例1的输入数据可以构造如下图所示的图结构:
基于该图,以hit
为图的起点,以cog
为终点进行广度优先搜索,寻找hit
到cog
的最短路径。下图即为答案其中的一条路径。
由于要求输出所有的最短路径,因此需要记录遍历路径,然后通过DFS得到所有的最短路径。
2、代码实现
package Q0199.Q0126WordLadderII;
import java.util.*;
/*
[Hard]
The basic idea is:
1). Use BFS to find the shortest distance between start and end, tracing the distance of crossing nodes from
start node to end node, and store node's next level neighbors to HashMap;
2). Use DFS to output paths with the same distance as the shortest distance from distance HashMap: compare if
the distance of the next level node equals the distance of the current node + 1.
*/
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
List<List<String>> res = new ArrayList<>();
if (wordList.size() == 0) return res;
Set<String> start = new HashSet<>();
Set<String> end = new HashSet<>();
Set<String> dict = new HashSet<>(wordList);
if (!dict.contains(endWord)) return res;
Map<String, List<String>> map = new HashMap<>();
start.add(beginWord);
end.add(endWord);
bfs(map, start, end, dict, false);
List<String> path = new ArrayList<>();
path.add(beginWord);
dfs(map, res, path, beginWord, endWord);
return res;
}
private void bfs(Map<String, List<String>> map, Set<String> start, Set<String> end, Set<String> dict, boolean reverse) {
if (start.isEmpty()) return;
if (start.size() > end.size()) {
bfs(map, end, start, dict, !reverse);
return;
}
boolean finish = false;
Set<String> nextLevel = new HashSet<>();
dict.removeAll(start);
for (String s : start) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length; i++) {
char old = word[i];
for (char c = 'a'; c <= 'z'; c++) {
word[i] = c;
String w = new String(word);
if (dict.contains(w)) {
if (end.contains(w)) finish = true;
else nextLevel.add(w);
String key = reverse ? w : s;
String val = reverse ? s : w;
if (!map.containsKey(key)) map.put(key, new ArrayList<>());
map.get(key).add(val);
}
}
word[i] = old;
}
}
if (!finish) bfs(map, nextLevel, end, dict, reverse);
}
private void dfs(Map<String, List<String>> map, List<List<String>> res, List<String> path, String begin, String end) {
if (begin.equals(end)) {
res.add(new ArrayList<>(path));
return;
}
if (!map.containsKey(begin)) return;
for (String s : map.get(begin)) {
path.add(s);
dfs(map, res, path, s, end);
path.remove(path.size() - 1);
}
}
}
3、复杂度分析
时间复杂度:
标签:0126,end,map,res,Ladder,II,start,new,path 来源: https://www.cnblogs.com/junstat/p/16286160.html