Word Ladder**

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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.

 

Analyse: Refered to this

Runtime: 276ms. 

 1 class Solution {
 2 public:
 3     int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
 4         wordDict.insert(endWord); //consider the string set as a graph
 5         queue<pair<string, int> > q;
 6         q.push(make_pair(beginWord, 1)); //start from the beginWord
 7         
 8         while(!q.empty()){
 9             string s = q.front().first; //string to be compared
10             int result = q.front().second; //the length of the ladder
11             
12             if(s == endWord) return result; //reach to the last string
13             q.pop();
14             vector<string> neighbours = findNeighbours(s, wordDict); //find all neighbour string to the s
15             for(int i = 0; i < neighbours.size(); i++)
16                 q.push(make_pair(neighbours[i], result + 1));
17         }
18         return 0;
19     }
20     
21     vector<string> findNeighbours(string s, unordered_set<string>& wordDict){
22         vector<string> result;
23         for(int i = 0; i < s.length(); i++){
24             char temp = s[i];
25             for(int j = 0; j < 26; j++){// O(26 * s.length())
26                 if(temp == 'a' + j) continue; //if the character is the same, then move to the next character
27                 s[i] = 'a' + j;
28                 if(wordDict.find(s) != wordDict.end()){
29                     result.push_back(s);
30                     wordDict.erase(s);
31                 }
32             }
33             s[i] = temp;
34         }
35         return result;
36     }
37 };

 

posted @ 2015-09-03 13:03  amazingzoe  阅读(119)  评论(0编辑  收藏  举报