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.
题意:
给定两个单词(起始单词和终止单词),和一本字典。找到从起始单词到终止单词的最短转换路径。
要求:每次只能转换一个字母
每个转换后的单词都必须在字典里面
例如”hit“为起始单词,"cog"为终止单词
字典为{"hot","dot","dog","lot","log"}
其中一条最短路径为"hot","dot","dog","lot","log"
Note: 所有的单词长度都相同
单词中都是小写字母
分类:字符串,图,广度搜索
解法1:基本思路和Word Ladder相同。关键在于存储所有的路径。
为了存储路径,需要为每个节点增加一个pre指针指向它的前一个节点。
另外注意,在遍历某一层的时候,如果节点a找到了下一个节点next,不要马上将其从字典里面删除
因为这一层的某个节点b,也可能下一层节点也是它next。
如果你删除了,那么这个b就找不到next了,而这也是一条路径。
所以合适的做法是,当这一层全部遍历完,我们才删除已经访问过的下一层节点。
这就需要我们记录下一层访问过的节点,在代码里面我们用visited来记录。
- public class Solution {
- public List<List<String>> findLadders(String start, String end, Set<String> dict) {
- class WordNode{
- String word;
- int step;
- WordNode pre;
- public WordNode(String word, int step,WordNode pre) {
- this.word = word;
- this.step = step;
- this.pre = pre;
- }
- }
-
- ArrayList<List<String>> res = new ArrayList<List<String>>();
- dict.add(end);
- HashSet<String> visited = new HashSet<String>();
- HashSet<String> unvisited = new HashSet<String>();
- unvisited.addAll(dict);
- Queue<WordNode> queue = new LinkedList<WordNode>();
- queue.add(new WordNode(start,1,null));
- int preNumSteps = 0;
- int minStep = 0;
-
- while(!queue.isEmpty()){
- WordNode cur = queue.poll();
- int currNumSteps = cur.step;
- if(cur.word.equals(end)){
- if(minStep == 0){
- minStep = cur.step;
- }
-
- if(cur.step == minStep && minStep !=0){
- ArrayList<String> t = new ArrayList<String>();
- t.add(cur.word);
- while(cur.pre !=null){
- t.add(0, cur.pre.word);
- cur = cur.pre;
- }
- res.add(t);
- continue;
- }
- }
- if(preNumSteps < currNumSteps){
- unvisited.removeAll(visited);
- }
- preNumSteps = currNumSteps;
- char[] arr = cur.word.toCharArray();
- for(int i=0;i<arr.length;i++){
- for(int c='a';c<='z';c++){
- char temp = arr[i];
- if(c!=temp){
- arr[i] = (char) c;
- }
- String str = new String(arr);
- if(unvisited.contains(str)){
- queue.add(new WordNode(str, currNumSteps+1,cur));
- visited.add(str);
- }
- arr[i] = temp;
- }
- }
- }
- return res;
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47337157