LeetCode_Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, 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. |
DFS 小数据AC:
class Solution { public: bool check(const string & a, const string &b) { int num = 0; if(a.size() != b.size()) return false; for(int i = 0; i< a.size() ; i++) { if(a[i] != b[i]) num++; } return num == 1; } void DFS(const string &start, const string &end, unordered_set<string> &dict, vector<bool> &flag, int nums){ if(start == end ){ res = res > nums ? nums : res; return ; } int i;auto it = dict.begin(); for( i= 0; it != dict.end(); it++,i++) if(flag[i] == false && check(start,*it)) { flag[i] = true; DFS(*it,end,dict, flag, nums+1); flag[i] = false; } } int ladderLength(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function res = dict.size() + 1 ; vector<bool> flag(dict.size(), false); DFS(start, end, dict, flag, 0); if(res == dict.size() + 1) return 0; return res +1 ; } private : int res; };
BFS: 过大数据
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function if(start.size() != end.size()) return 0; if(dict.size() == 0) return 0; queue<string> myqueue, myqueueT; myqueue.push(start); int depth = 1; while(!myqueue.empty()){ depth++; while(!myqueue.empty()){ string str = myqueue.front(); myqueue.pop(); for(int i = 0; i < str.size() ; i++){ char temp = str[i] ; for(char c = 'a'; c <= 'z' ;c++){ if(c == temp) continue; str[i] = c; if(str == end) return depth; auto it = dict.find(str) ; if(it != dict.end() ){ myqueueT.push(str); dict.erase(it); } } str[i] = temp; } } myqueue.swap( myqueueT); } //don't find return 0; } };
--------------------------------------------------------------------天道酬勤!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 个人数据保全计划:从印象笔记迁移到joplin
· Vue3.5常用特性整理
· 重拾 SSH:从基础到安全加固
· 并发编程 - 线程同步(一)