【leetcode】Word Ladder

Word Ladder

 Total Accepted: 24823 Total Submissions: 135014My Submissions

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, 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.
Hide Tags
 Breadth-first Search
 
 
利用广度优先搜索,找到元素的深度即可
寻找相差一个字符的字符串时,考虑采用替换字符的方式寻找,遍历dict在dict很长时,会耗时
 
 1 int ladderLength(string start, string end, unordered_set<string> &dict) {
 2         int n=start.size();
 3         if(n<1||n!=end.size())
 4         {
 5             return 0;
 6         }
 7         if(start==end)
 8         {
 9             return 1;
10         } 
11  
12         int level=2;
13         queue<string> q;
14         q.push(start);   
15         //count用来记录每一个深度的元素的个数    
16         int count=1;       
17         while(1)
18         {          
19         start=q.front();
20         q.pop();
21         count--;       
22         for(int i=0;i<start.length();i++)
23         {
24             string ori=start;
25 //每次修改一个字符,看是否在字典中能找到
26             for(char ch='a';ch<='z';ch++)
27             {
28                 if(start[i]==ch)continue;
29                
30                 start[i]=ch;
31                 if(start==end) return level;
32       //如果能找到,则用queue记录下下一层深度的元素
33                 if(dict.find(start)!=dict.end())
34                 {
35                     dict.erase(start);
36                     q.push(start);
37                 }
38                 start=ori;
39             }
40         }
41       
42 //没有下一层深度了,或者dict已经为空
43         if(q.empty()||dict.empty())
44         {
45             break;
46         }
47        
48         //count为0,说明该level的元素已经被遍历完了
49         if(count==0)
50         {
51             level++;
52             count=q.size();
53         }    
54         }
55         return 0;
56     }
 
原文地址:https://www.cnblogs.com/reachteam/p/4251658.html