【word ladder】cpp

题目:

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:

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

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

代码:

复制代码
class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
            queue<string> que;
            que.push(beginWord); que.push("");
            int len = 1;
            while ( !que.empty() )
            {
                string curr = que.front();
                que.pop();
                if (curr!="")
                {
                    for ( size_t i = 0; i < curr.size(); ++i )
                    {
                        char curr_c = curr[i];
                        for ( char c='a'; c <= 'z'; ++c )
                        {
                            if (c==curr_c) continue;
                            curr[i] = c;
                            if (curr==endWord) return len+1;
                            if ( wordDict.find(curr)!=wordDict.end() )
                            {
                                que.push(curr);
                                wordDict.erase(curr);
                            }
                        }
                        curr[i] = curr_c;
                    }
                }
                else if ( !que.empty() )
                {
                    len++;
                    que.push("");
                }
            }
            return 0;
    }
};
复制代码

tips:

学习了BFS的思路。

维护一个queue;存放当前word在dict中的所有邻居;末尾加一个空字符""来标示深入一层。

http://www.cnblogs.com/TenosDoIt/p/3443512.html

http://blog.csdn.net/niaokedaoren/article/details/8884938

=============================================

第二次过这道题,上来就打着bfs的幌子写了一个dfs的算法,结果是超时。但也想了一下为什么不能用dfs,dfs会超时的原因是啥:

比如:beginWord = "ab" wordDict{"cb, db"}

如果用dfs的话,就可能会建立出来ab→cb→db 这样即走了冤枉路,也不是最短。

复制代码
class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        queue<string> curr;
        queue<string> next;
        int len = 1;
        curr.push(beginWord);
        while ( !curr.empty() )
        {
            while ( !curr.empty() )
            {
                string word = curr.front();
                curr.pop();
                for ( int i=0; i<word.size(); ++i )
                {
                    char ori = word[i];
                    for ( char c='a'; c<='z'; ++c )
                    {
                        if ( c==ori ) continue;
                        word[i] = c;
                        if ( word==endWord ) return len+1;
                        if ( wordDict.find(word)!=wordDict.end() )
                        {
                            next.push(word);
                            wordDict.erase(word);
                        }
                    }
                    word[i] = ori;
                }
            }
            if ( next.empty() ) return 0;
            len++;
            swap(next, curr);
        }
        return 0;
    }
};
复制代码

 

posted on   承续缘  阅读(169)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示