首页 > 其他 > 详细

[LeetCode]Word Ladder

时间:2014-03-14 18:59:46      阅读:346      评论:0      收藏:0      [点我收藏+]

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.

思考:BFS。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        queue<pair<string,int>> q;
        unordered_set<string> visited;
        q.push(make_pair(start, 1));
        visited.insert(start);
        while (!q.empty())
        {
            string curStr = q.front().first;
            int curStep = q.front().second;
            q.pop();
            for (int i = 0; i < curStr.size(); ++i)
            {
                string tmp = curStr;
                for (int j = 0; j < 26; ++j)
                {
                    tmp[i] = j+‘a‘;
                    if(tmp == end)
                        return curStep+1;
                    if(visited.find(tmp) == visited.end() && dict.find(tmp) != dict.end())
                    {
                        q.push(make_pair(tmp, curStep+1));
                        visited.insert(tmp);
                    }
                }
            }
        }
        return 0;
    }
};

  

[LeetCode]Word Ladder,布布扣,bubuko.com

[LeetCode]Word Ladder

原文:http://www.cnblogs.com/Rosanna/p/3598384.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!