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:

  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 length5.

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 1;
6
        queue<string> que;
7
        que.push(start);
8
        int pre_size = 1;//上一层宽度
9
        int len = 1;//层高
10
        while (!que.empty()){
11
            int cur_size = 0;//当前层宽度
12
            for (int i=0; i<pre_size; ++i){
13
                string str = que.front();
14
                que.pop();
15
                for (int j=0; j<str.size(); ++j){
16
                    char old = str[j];
17
                    for (char c='a'; c<='z'; ++c){
18
                        if (c == old)
19
                            continue;
20
                        str[j] = c;
21
                        if (str == end)
22
                            return len+1;
23
                        if (dict.find(str) != dict.end()){
24
                            que.push(str);
25
                            dict.erase(str);
26
                            ++cur_size;
27
                        }
28
                    }
29
                    str[j] = old;
30
                }
31
            }
32
            pre_size = cur_size;
33
            ++len;
34
        }
35
        return 0;
36
    }
37
};
您的代码已保存

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值