LeetCode: 126. Word Ladder II

LeetCode: 126. Word Ladder II

最近工作和毕设压力比较大, 刷 LeetCode 有点不在状态,代码可能有点难看。不过,整体的思路应该是没有问题的。

题目描述

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.

题目大意: 根据给定的开始结束单词以及字母表,找到所有从开始单词到结束单词的最短路径。要求路径上的每个单词之间只有一个字母之差。

解题思路 —— 广度搜索

广度搜索可以直接求到最短路径。我们可以在计算最短路径的过程中,记录下当前到达节点的最短路径的前驱,然后推出所有的路径。如下图:

前驱

虽然 dot <--> lot, dog <--> log 等路径也存在,但其不是到达相应节点的最短路径,因此可以忽略掉。如下图:

不是最短路径

AC 代码

class Solution {
private:
    // 记录广度搜索状态的结构
    struct LadderState
    {
        vector<string> frontState;  // 记录当前状态是由哪些状态转换而来
        int level;                  // 记录当前状态的层数
    };
private:
    // 判断两个单词是否只相差一个字母
    bool isNear(string lhv, string rhv)
    {
        if(lhv.size() != rhv.size()) return false;

        int cnt = 0;
        for(int i = 0; i < lhv.size() && cnt < 2; ++i)
        {
            if(lhv[i] != rhv[i])
            {
                ++cnt;
            }
        }

        return (cnt == 1);
    }    
    // 返回到达 endWord 的所有最短路径
    set<vector<string>> recoverPaths(string beginWord, string endWord, map<string, LadderState>& wordStates)
    {
        if(beginWord == endWord) return {{beginWord}};
        set<vector<string>> paths;
        for(size_t i = 0; i < wordStates[endWord].frontState.size(); ++i)
        {
            set<vector<string>> curPaths = recoverPaths(beginWord, wordStates[endWord].frontState[i], wordStates);
            for(auto path : curPaths)
            {
                path.push_back(endWord);
                paths.insert(path);
            }
        }

        return paths;
    }
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        multimap<string, string> wordDir; //wordDir[i] = j 表示 i 到 j 只有一个字母不同

        // 计算距离,将相邻的节点存入 wordDir 中
        for(int i = 0; i < wordList.size(); ++i)
        {
            for(int j = i+1; j < wordList.size(); ++j)
            {
                if(isNear(wordList[i], wordList[j]))
                {
                    wordDir.insert({wordList[i], wordList[j]});
                    wordDir.insert({wordList[j], wordList[i]});
                }
            }
        }
        for(int i = 0; i < wordList.size(); ++i)
        {
            if(isNear(wordList[i], beginWord))
            {
                wordDir.insert({wordList[i], beginWord});
                wordDir.insert({beginWord, wordList[i]});
            }
        }

        // 初始化各个节点的状态
        map<string, LadderState> wordStates;
        for(size_t i = 0; i < wordList.size(); ++i)
        {
            wordStates[wordList[i]] = { {}, 0};
        }
        wordStates[beginWord] = { {}, 0 };

        // 计算最短路径
        queue<string> que;
        unordered_set<string> flags;

        que.push(beginWord);
        que.push("#");
        flags.insert(beginWord);
        int stepNum = 0;

        while(!que.empty())
        {
            string curWord = que.front();
            que.pop();

            if(curWord == "#") 
            {
                ++stepNum;
                if(!que.empty()) que.push("#");
                continue;
            }

            if(curWord == endWord)
            {
                continue;
            }

            for(auto iter = wordDir.find(curWord); iter != wordDir.end() && iter->first == curWord; ++iter)
            {
                if(flags.find(iter->second) == flags.end())
                {
                    flags.insert(iter->second);
                    que.push(iter->second);
                    wordStates[iter->second].level = wordStates[curWord].level + 1;
                }

                if(wordStates[iter->second].level == wordStates[curWord].level + 1)
                {
                    wordStates[iter->second].frontState.push_back(curWord);
                }
            }
        }

        // 根据 wordStates 恢复各个路径
        set<vector<string>> paths = recoverPaths(beginWord, endWord, wordStates);
        vector<vector<string>> ans(paths.begin(), paths.end());
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值