Word Ladder I & II (Leetcode 127, 126)

Word Ladder I:
https://leetcode.com/problems/word-ladder/

对于I,BFS层序遍历就行。为避免重复遍历,wordDict将找到的neighbor单词删掉。同时,找到下一个合适的单词(one character away) 的办法,是遍历该单词所有字符,将其替换成另外25个,然后查找WordDict,看新单词是否存在。

int ladderLength(string beginWord, string endWord, unordered_set& wordList) {
        wordList.insert(endWord);
        queue> q;
        q.push({beginWord, 1});
        while(!q.empty()){
            string cur = q.front().first; 
            int lvl = q.front().second; q.pop();
            if(cur == endWord) return lvl;
            vector neighbors = findNeighbors(cur, wordList);
            for(string it : neighbors){
                q.push({it, lvl+1});
            }
        }
        return 0;
    }
    
    vector findNeighbors(string cur, unordered_set& wordList){
        vector ret;
        for(int i=0; i

Word Ladder II:
https://leetcode.com/problems/word-ladder-ii/

II 则非常复杂,是leetcode里面acceptance非常低的题目之一。难点在于要返回所有的最短路径。不仅DFS搜索,还要选择最短的。
九章的思路是建立在 I 的基础上,从endWord开始往回BFS (同 I 一样)。这样的目的是建立每个单词与endWord的最短距离。然后再从起点DFS,每次判断neighbor 单词的距离是否小1,只有小1,才加入result set继续往下搜索。

class Solution {
public:
    vector> findLadders(string beginWord, string endWord, unordered_set &wordList) {
        vector> allcomb;
        wordList.insert(beginWord);
        wordList.insert(endWord);
        unordered_map mp;
        unordered_map> nexts;
        bfs(endWord, wordList, mp, nexts);
        /*for(auto it : mp){
            cout << it.first << " " << it.second << endl;
        }*/
        vector comb;
        comb.push_back(beginWord);
        dfs(allcomb, comb, mp, nexts, beginWord, endWord);
        return allcomb;
    }
    
    void dfs(vector> &allcomb, vector &comb, unordered_map &mp, unordered_map> &nexts, string cur, string end){
        
        if(cur == end){
            allcomb.push_back(comb);
            return;
        }
        vector neighbors = nexts[cur];
        for(int i=0; i &dict, unordered_map &mp, unordered_map> &nexts){
        queue> q;
        q.push({end, 0});
        mp[end] = 0;
        while(!q.empty()){
            string cur = q.front().first;
            int lvl = q.front().second; q.pop();
            vector neighbors = findNeighbors(cur, dict);
            for(int i=0; i findNeighbors(string cur, unordered_set &dict){
        vector ret;
        for(int i=0; i

注意细节:要设 mp[end] = 0,并insert beginWord to set;

你可能感兴趣的:(Word Ladder I & II (Leetcode 127, 126))