您的位置:首页 > 其它

leetcode题解-126. Word Ladder II

2017-06-20 10:42 344 查看
题目:

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.


这道题挺难的==先翻译一下题目,其实是给定了一个beginWord和endWord,还有可用的单词列表,然后我们需要在每次只转换一个字符且转换后的字符在wordList中的情况下,将beginWord在最短步骤内转换为endWord,看到题目没有什么好的思路,然后正好前两天有同学问我dfs的一道题目,发现与本题有那么一丢丢的相似,然后就想着强行套dfs,中途遇到了几个问题:

如何解决每次只转换一个字符

如何解决在最短步骤内完成转换

然后也是想了很久才把这道题目做出来,代码如下所示:

static int min = Integer.MAX_VALUE;
public static List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
//存储返回结果
List<List<String>> res = new ArrayList<>();
//存储当前的路径
List<String> tmp = new ArrayList<>();
tmp.add(beginWord);
//因为题目要求endWord必须在wordList中,否则报错
if(!wordList.contains(endWord))
return res;
//调用dfs方法求解
dfs(res, tmp, beginWord, endWord, wordList);
//此时res中存储了所有的可行解,但有些并不是步骤最短解,所以需要用全局变量min来记录最短步骤,然后将大于min的结果删除
for(int i=0; i<res.size(); i++){
if(res.get(i).size() > min) {
res.remove(i);
i--;
}
}
System.out.println(res.toString());
return res;
}
public static void dfs(List<List<String>> res, List<String> tmp, String beginWord, String endWord, List<String> wordList){
//dfs函数返回标志,当现在要遍历的单词与endWord只差一个字符时,说明已经满足要求,将其插入tmp,并将tmp插入res即可
if(isOne(beginWord, endWord)){
tmp.add(endWord);
min = Math.min(min, tmp.size());
res.add(new ArrayList<>(tmp));
tmp.remove(endWord);
return;
}
//否则,说明还未找到解,继续遍历数组
for(String tt : wordList){
//若当前词不在tmp中且与beginWord只差一个字符,则将其插入tmp,并继续调用dfs函数继续执行
if(!tmp.contains(tt) && isOne(beginWord, tt)){
tmp.add(tt);
dfs(res, tmp, tt, endWord, wordList);
//=当执行dfs找到一个可行解之后,删除当前词,继续遍历下一个词
tmp.remove(tt);
}

}
}
//判断两个词是否只相差一个字符
public static boolean isOne(String s, String t){
int k=0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i) != t.charAt(i))
k++;
}
if(k == 1)
return true;
else
return false;
}


恩,上面就是我的方法,但是,很明显,由于中间重复计算次数太多而且是先找出所有可行解之后在将非最优解去掉,所以算法效率很低,也爆出了超出时间限制的错误。所以去网上找了一下别人实现的方法,发现大部分都是先用BFS找到最短步骤数,并将一些相关信息使用HashMap保存,然后再使用DFS遍历保存下来的neighbor和distance信息,找出符合要求的结果,大概是因为Word Ladder I那个题目中延续下来的方法。先不管这么多,我们来看一下代码:

public List<List<String>> findLadders(String start, String end, List<String> wordList) {
HashSet<String> dict = new HashSet<String>(wordList);
List<List<String>> res = new ArrayList<List<String>>();
HashMap<String, ArrayList<String>> nodeNeighbors = new HashMap<String, ArrayList<String>>();// 保存每个节点的neighbor信息,也就是相差一个字符的所有组合
HashMap<String, Integer> distance = new HashMap<String, Integer>();// 记录每个字符串到beginWord的距离
ArrayList<String> solution = new ArrayList<String>();

dict.add(start);
bfs(start, end, dict, nodeNeighbors, distance);
dfs(start, end, dict, nodeNeighbors, distance, solution, res);
return res;
}

// BFS: Trace every node's distance from the start node (level by level).
private void bfs(String start, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance) {
for (String str : dict)
nodeNeighbors.put(str, new ArrayList<String>());
//使用队列进行BFS遍历
Queue<String> queue = new LinkedList<String>();
queue.offer(start);
distance.put(start, 0);

while (!queue.isEmpty()) {
int count = queue.size();
boolean foundEnd = false;
for (int i = 0; i < count; i++) {
String cur = queue.poll();
int curDistance = distance.get(cur);
ArrayList<String> neighbors = getNeighbors(cur, dict);

for (String neighbor : neighbors) {
nodeNeighbors.get(cur).add(neighbor);
if (!distance.containsKey(neighbor)) {// Check if visited
distance.put(neighbor, curDistance + 1);
if (end.equals(neighbor))// Found the shortest path
foundEnd = true;
else
queue.offer(neighbor);
}
}
}

if (foundEnd)
break;
}
}

// Find all next level nodes.
private ArrayList<String> getNeighbors(String node, Set<String> dict) {
ArrayList<String> res = new ArrayList<String>();
char chs[] = node.toCharArray();

for (char ch ='a'; ch <= 'z'; ch++) {
for (int i = 0; i < chs.length; i++) {
if (chs[i] == ch) continue;
char old_ch = chs[i];
chs[i] = ch;
if (dict.contains(String.valueOf(chs))) {
res.add(String.valueOf(chs));
}
chs[i] = old_ch;
}

}
return res;
}

// DFS: output all paths with the shortest distance.
private void dfs(String cur, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance, ArrayList<String> solution, List<List<String>> res) {
solution.add(cur);
if (end.equals(cur)) {
res.add(new ArrayList<String>(solution));
} else {
for (String next : nodeNeighbors.get(cur)) {
if (distance.get(next) == distance.get(cur) + 1) {
dfs(next, end, dict, nodeNeighbors, distance, solution, res);
}
}
}
solution.remove(solution.size() - 1);
}


上面这种方法可以击败67%的用户,可以说使用额外的存储空间大大的降低了时间复杂度,我想这也应该是一种常用的降低时间复杂度的方法吧,不过其内在的思路还是十分值得我们学习的。然后还找到一中可以击败97%的方法,想法更加完美,使用双向BFS来加速,具体思路可以参考链接,但是由于题目更改,现在代码是无法直接运行的,可以参考我改过之后的==代码入下:

public class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
//we use bi-directional BFS to find shortest path
List<List<String>> result = new ArrayList<List<String>>();
if(!wordList.contains(endWord))
return result;
HashSet<String> dict = new HashSet<String>(wordList);
Set<String> fwd = new HashSet<String>();
fwd.add(beginWord);

Set<String> bwd = new HashSet<String>();
bwd.add(endWord);

Map<String, List<String>> hs = new HashMap<String, List<String>>();
BFS(fwd, bwd, dict, false, hs);

//if two parts cannot be connected, then return empty list
if(!isConnected) return result;

//we need to add start node to temp list as there is no other node can get start node
List<String> temp = new ArrayList<String>();
temp.add(beginWord);

DFS(result, temp, beginWord, endWord, hs);

return result;
}

//flag of whether we have connected two parts
boolean isConnected = false;

public void BFS(Set<String> forward, Set<String> backward, Set<String> dict, boolean swap, Map<String, List<String>> hs){

//boundary check
if(forward.isEmpty() || backward.isEmpty()){
return;
}

//we always do BFS on direction with less nodes
//here we assume forward set has less nodes, if not, we swap them
if(forward.size() > backward.size()){
BFS(backward, forward, dict, !swap, hs);
return;
}

//remove all forward/backward words from dict to avoid duplicate addition
dict.removeAll(forward);
dict.removeAll(backward);

//new set contains all new nodes from forward set
Set<String> set3 = new HashSet<String>();

//do BFS on every node of forward direction
for(String str : forward){
//try to change each char of str
for(int i = 0; i < str.length(); i++){
//try to replace current char with every chars from a to z
char[] ary = str.toCharArray();
for(char j = 'a'; j <= 'z'; j++){
ary[i] = j;
String temp = new String(ary);

//we skip this string if it is not in dict nor in backward
if(!backward.contains(temp) && !dict.contains(temp)){
continue;
}

//we follow forward direction
String key = !swap? str : temp;
String val = !swap? temp : str;

if(!hs.containsKey(key)) hs.put(key, new ArrayList<String>());

//if temp string is in backward set, then it will connect two parts
if(backward.contains(temp)){
hs.get(key).add(val);
isConnected = true;
}

//if temp is in dict, then we can add it to set3 as new nodes in next layer
if(!isConnected && dict.contains(temp)){
hs.get(key).add(val);
set3.add(temp);
}
}

}
}

//to force our path to be shortest, we will not do BFS if we have found shortest path(isConnected = true)
if(!isConnected){
BFS(set3, backward, dict, swap, hs);
}
}

public void DFS(List<List<String>> result, List<String> temp, String start, String end, Map<String, List<String>> hs){
//we will use DFS, more specifically backtracking to build paths

//boundary case
if(start.equals(end)){
result.add(new ArrayList<String>(temp));
return;
}

//not each node in hs is valid node in shortest path, if we found current node does not have children node,
//then it means it is not in shortest path
if(!hs.containsKey(start)){
return;
}

for(String s : hs.get(start)){
temp.add(s);
DFS(result, temp, s, end, hs);
temp.remove(temp.size()-1);

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: