LintCode-121: Word Ladder II (经典搜索难题 BFS+DFS)

  1. Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, output sequence in dictionary order.
Transformation rule such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
Example
Example 1:

Input:start = “a”,end = “c”,dict =[“a”,“b”,“c”]
Output:[[“a”,“c”]]
Explanation:
“a”->“c”
Example 2:

Input:start =“hit”,end = “cog”,dict =[“hot”,“dot”,“dog”,“lot”,“log”]
Output:[[“hit”,“hot”,“dot”,“dog”,“cog”],[“hit”,“hot”,“lot”,“log”,“cog”]]
Explanation:
1.“hit”->“hot”->“dot”->“dog”->“cog”
2.“hit”->“hot”->“lot”->“log”->“cog”
The dictionary order of the first sequence is less than that of the second.
Notice
All words have the same length.
All words contain only lowercase alphabetic characters.
At least one solution exists.

解法1:
这道题是超级经典难题。一个是它本身就难,再一个就是很难AC(要么空间不够,要么时间超时)。我参考的网上的解法。
以下面的input为例:
start = hit
end = cog
dict = [hot,dot,dog,lot,log,dof,mit,sit,set,mog,mig,seg,nax,max]
Return
[[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”],
[“hit”,“mit”,“mig”,“mog”,“cog”]]

我们先用BFS找到一条最短路径,可能是上面3个solution中的一种。
可以发现BFS遍历到的word是有层级先后顺序的:

level 1: [hit]
level 2: [mit, sit, hot]
level 3: [mig, set, dot, lot]
level 4: [mog, seg, dof, dog, log]
level 5: [cog]

我们在调用BFS的时候,顺便用Str2NextStrs记下每个string的下一个string的集合,比如说hot->{dot, lot},然后用StrSteps记下每个string到start的步数,比如说mit->2, seg->4。然后我们就可以用DFS来找最短路径了,因为最短路径就是在每个level中挑一个可行的搭起来的。
注意上面图中的level1-5对应Str2NextStrs,包含了BFS分层遍历的所有可能节点。

class Solution {
public:
    /*
     * @param start: a string
     * @param end: a string
     * @param dict: a set of string
     * @return: a list of lists of string
     */
    map<string, vector<string>> Str2NextStrs;
    vector<vector<string>> results;
    
    vector<vector<string>> findLadders(string &start, string &end, unordered_set<string> &dict) {
        map<string, int> StrSteps;
        vector<string> sol;
        dict.insert(end); //否则如果dict里面没有end,输出[]
        bfs(start, end, dict, StrSteps);
        sol.push_back(start);
        dfs(start, end, StrSteps, sol);
        return results;
    }
    
    
    void bfs(string& start, string& end, 
             unordered_set<string> &dict, 
             map<string, int> &StrSteps) {
        queue<string> q;
        q.push(start);
        StrSteps[start] = 0;
        while (!q.empty()) {
            
            string s = q.front(); q.pop();
            if (s == end) break;
            
            vector<string> nextStrs;
            
            for (int i = 0; i < s.size(); ++i) {
                string newStr = s;
                for (char c = 'a'; c <= 'z'; c++) {
                    newStr[i] = c;
                    if (c == s[i] || dict.find(newStr) == dict.end()) 
                        continue;
    
                    if (StrSteps.find(newStr) == StrSteps.end()) {
                        q.push(newStr);
                        StrSteps[newStr] = StrSteps[s] + 1;
                    }
                    nextStrs.push_back(newStr);
                }
            }
            Str2NextStrs[s] = nextStrs;
        }
    }
    
    
    void dfs(string& start, string& end, 
             map<string, int> &StrSteps, 
             vector<string> &sol){
  
        if (start == end) 
            results.push_back(sol);
        
        vector<string> nextStrs = Str2NextStrs[start];
        for (int i = 0; i < nextStrs.size(); i++) {
            
            if (StrSteps[nextStrs[i]] != StrSteps[start] + 1) continue;
            
            sol.push_back(nextStrs[i]);
            dfs(nextStrs[i], end, StrSteps, sol);
            sol.pop_back();
        }
    }
};

代码同步在
github.com/luqian2017/Algorithm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值