[LeetCode-127] Word Ladder

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

 

BPS。

 

 1 class Solution {
 2 public:
 3     int ladderLength(string start, string end, unordered_set<string> &dict) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         // bps
 7         queue<pair<string, int> > path;
 8         unordered_set<string> visited;
 9         path.push(make_pair(start, 1));
10         visited.insert(start);
11         string cur_string, str_left, str_right, str_conv;
12         int cur_step;
13         
14         while (!path.empty()) {
15             cur_string = path.front().first;
16             cur_step = path.front().second;
17             for (int i = 0; i < cur_string.length(); ++i) {
18                 str_left = cur_string.substr(0, i);
19                 str_right = cur_string.substr(i + 1, cur_string.length() - i - 1);
20                 for (char c = 'a'; c <= 'z'; ++c) {
21                     str_conv = str_left;
22                     str_conv.append(1, c);
23                     str_conv.append(str_right);
24                     
25                     if (0 == str_conv.compare(end)) {
26                         return cur_step + 1;
27                     }
28                     if ((dict.find(str_conv) != dict.end()) && (visited.find(str_conv) == visited.end())) {
29                         visited.insert(str_conv);
30                         path.push(make_pair(str_conv, cur_step + 1));
31                     }
32                 }
33             }
34             path.pop();
35         }
36         return 0;
37     }
38 };
View Code

 

posted on 2013-08-29 22:22  似溦若岚  阅读(230)  评论(0编辑  收藏  举报

导航