【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:
- 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"]
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; } };
分类:
cpp刷Leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?