您的位置:首页 > 编程语言 > Java开发

[LeetCode][Java] Word Ladder II

2015-07-28 16:16 330 查看

题目:

Given 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

For 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.

题意:

与题目《Word Ladder》不同的地方是,这里不是求最短变换序列的长度,而是返回所有的满足条件的最短序列。



算法分析:

参考了博客http://blog.csdn.net/worldwindjp/article/details/19301355

先BFS生成找到end时的生成树,标记出每个单词所在的层数。然后从目标用DFS往回找,过了大数据

AC代码:

<span style="font-family:Microsoft YaHei;font-size:10px;">public class Solution
{
//记录每个单词所在的层数
HashMap<String,Integer> path = new HashMap<String,Integer>();
//bfs生成path
void bfs(String start, String end, HashSet<String> dict)
{
Queue queue = new LinkedList<String>();
queue.add(start);
path.put(start,0);
String current;
while(!queue.isEmpty())
{
current = (String)queue.poll();
if(current==end)
{
continue;
}
for(int i=0;i<current.length();i++)
{
char[] strCharArr = current.toCharArray();
for(char ch='a';ch<='z';ch++)
{
if(strCharArr[i]==ch)
{
continue;
}
strCharArr[i] = ch;
String newWord = new String(strCharArr);
if(newWord.equals(end)==true||dict.contains(newWord))
{
//每个单词在path中只能出现一次,也就是每个单词只能出现在一层中,这样就很巧妙的解决了环的问题。
if(path.get(newWord)==null)
{
int depth = (int)path.get(current);
path.put(newWord,depth + 1);
queue.add(newWord);
}
}
}
}
}
}
//从目标单词往回找开始单词,记录所有路径
void dfs(String start, String end, HashSet<String> dict, ArrayList<String> pathArray,ArrayList<ArrayList<String>> result)
{
//找到了,需要reverse加入的所有单词
if(start.equals(end)==true)
{
pathArray.add(start);
Collections.reverse(pathArray);
result.add(pathArray);
return;
}
if(path.get(start)==null)
{
return;
}
pathArray.add(start);
int nextDepth = (int)path.get(start) - 1;
for(int i=0;i<start.length();i++)
{
char[] strCharArr = start.toCharArray();
for(char ch='a';ch<='z';ch++)
{
if(strCharArr[i]==ch)
{
continue;
}
strCharArr[i] = ch;
String newWord = new String(strCharArr);
//只相差一个字母同时这个单词所在的层数也是当前单词的上一层
if(path.get(newWord)!=null&&(path.get(newWord)==nextDepth))
{
ArrayList<String> newPathArray = new ArrayList<String>(pathArray);
dfs(newWord,end,dict,newPathArray,result);
}
}
}
}

public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict)
{
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
ArrayList<String> path = new ArrayList<String>();
if(start==null||end==null||start.length()!=end.length())
{
return result;
}
bfs(start, end, dict);
dfs(end,start, dict, path, result);
return result;
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: