代码改变世界

leetcode - Word Ladder

2013-12-16 18:19  张汉生  阅读(207)  评论(0编辑  收藏  举报

 

 1 //bfs
 2 class Solution {
 3 public:
 4     typedef unordered_map<string, int> MyHashMap;
 5     int ladderLength(string start, string end, unordered_set<string> &dict) {
 6         if (start == end)
 7             return 1;
 8         if (start.length() != end.length())
 9             return 0;
10         queue<string> qs;
11         int len = start.length();
12         qs.push(start);
13         MyHashMap mp;
14         mp[start] = 1;
15         while (!qs.empty()){
16             string cur = qs.front();
17             qs.pop();
18             for (int i = 0; i < len; i++){
19                 for (int j = 0; j < 26; j++){
20                     string tmp = cur;
21                     tmp[i] = 'a'+j;
22                     if (tmp == end)
23                         return mp[cur]+1;
24                     if (dict.find(tmp) == dict.end())
25                         continue;
26                     if (mp.find(tmp) != mp.end())
27                         continue;
28                     qs.push(tmp);
29                     mp[tmp] = mp[cur] + 1;
30                 }
31             }
32         }
33         return 0;
34     }
35 };