LeetCode每日一题:单词梯 2

问题描述

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.

问题分析

这题比起上一题来说要输出所有的结果,原本想在其中加入一个ArrayList,但是直接超时,没有什么好的想法,就上网看了其他大佬的做法。

  • 解决方法
    先BFS生成找到end时的生成树,标记出每个单词所在的层数。然后从目标用DFS往回找

代码实现

代码来自 Leetcode Word Ladder II 解题报告 - 算法的天空 - 博客频道 - CSDN.NET

public class Solution {
    //记录每个单词所在的层数
    HashMap path = new HashMap();
    //bfs生成path
    void bfs(String start, String end, HashSet dict) {
        Queue queue = new LinkedList();
        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 dict, ArrayList pathArray,ArrayList> 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 newPathArray = new ArrayList(pathArray);
                    dfs(newWord,end,dict,newPathArray,result);
                }
            }
        }
    }
    
    public ArrayList> findLadders(String start, String end, HashSet dict) {
        ArrayList> result = new ArrayList>();
        ArrayList path = new ArrayList();
        if(start==null||end==null||start.length()!=end.length()) {
            return result;
        }
        bfs(start, end, dict);
        dfs(end,start, dict, path, result);
        return result;
    }
}

你可能感兴趣的:(LeetCode每日一题:单词梯 2)