Word Ladder

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 and each intermediate word must exist in the dictionary. For example, given:

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

One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should 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.

 1 class Solution{
 2 public:
 3     int ladderlength(string start,string end,unordered_set<string> &dict){
 4         if(start == end){
 5             return 0;
 6         }
 7         unordered_map<string,int> len;
 8         len[start] = 1;
 9         queue<string> q;
10         for(q.push(start);!q.empty();q.pop()){
11             string word = q.front();
12             int step = len[start] + 1;
13             for(int i = 0;i<word.length();i++){
14                 for(char ch = 'a';ch <= 'z';++ch){
15                     if(word[i] != ch){
16                         char temp = word[i];
17                         word[i] = ch;
18                         if((dict.find(word)!=dict.end())&&(len.find(word)==len.end())){
19                             if(start == end){
20                                 return step;
21                             }
22                             q.push(word);
23                             len[word] = step;
24                          }
25                         word[i] = temp;
26                     }
27                 }
28             }
29         }
30         return 0;
31     }
32 }

 

转载于:https://www.cnblogs.com/Dillonn/p/4546105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值