Leetcode#127 Word Ladder

原题地址

 

BFS

Word Ladder II的简化版(参见这篇文章

由于只需要计算步数,所以简单许多。

 

代码:

 1 int ladderLength(string start, string end, unordered_set<string> &dict) {
 2         if (start == end)
 3             return 0;
 4             
 5         unordered_set<string> old;
 6         queue<string> layer;
 7         int len = 1;
 8         
 9         layer.push(start);
10         while (!layer.empty()) {
11             queue<string> nextLayer;
12             while (!layer.empty()) {
13                 string str = layer.front();
14                 layer.pop();
15                 if (str == end)
16                     return len;
17                 for (int i = 0; i < str.length(); i++) {
18                     for (char j = 'a'; j <= 'z'; j++) {
19                         string next = str;
20                         next[i] = j;
21                         if (old.find(next) == old.end() && dict.find(next) != dict.end()) {
22                             old.insert(next);
23                             nextLayer.push(next);
24                         }
25                     }
26                 }
27             }
28             len++;
29             layer = nextLayer;
30         }
31         
32         return 0;
33 }

 

转载于:https://www.cnblogs.com/boring09/p/4262998.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值