word ladder

 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         if( dict.empty() )  return 0;
 7         if( start == end ) return 0; 
 8         int len = 0;
 9         map<string,string> path;
10         queue<string> words;
11         words.push(start );
12         while( !words.empty() )
13         {
14             string str = words.front();
15             words.pop();
16             
17             for(int i=0;i<str.length(); i++ )
18             {
19                 string tmp = str;
20                 for(char c = 'a'; c <= 'z'; c++ )
21                 {
22                     if( c==str[i] )  continue;
23                     tmp[i] = c;
24                     if( tmp == start )  continue;
25                     if( tmp == end )
26                     {
27                         path[ end ] = str;
28                         string s = end;           
29                         while( path[s] != start )
30                         {
31                             len ++;
32                             s = path[s];
33                         }
34                         return len + 2;
35                     }
36                     if( dict.find( tmp ) != dict.end() && path.find(tmp)==path.end() )
37                     {
38                         path[tmp] = str;
39                         words.push( tmp );
40                         
41                     }
42                     
43                 }
44             }
45         }
46         return 0;
47         
48         
49         
50     }
51 };

 

posted on 2013-09-01 16:09  jumping_grass  阅读(169)  评论(0)    收藏  举报

导航