-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordLadder.cpp
58 lines (53 loc) · 1.53 KB
/
WordLadder.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// WordLadder.cpp
//
//
// Created by 廷芳 杜 on 7/13/13.
// Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//
#include <iostream>
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( start == end ) return 1;
if( dict.empty() ) return 0;
int len = 1;
queue<string> u;
u.push( start );
u.push( "" );
while( !u.empty() )
{
string v = u.front();
u.pop();
if( v == "" ) //whole level has been traversaled.
{
len = len+1;
if( !u.empty() ) u.push( "" );
}
else
{
if( v == end ) return len;
else
{
string temp = v;
for( int i = 0; i < v.length(); ++i )
{
for( int j = 'a' ; j <= 'z'; ++j )
{
v[i] = j;
if( dict.find(v) != dict.end() ) //find the word
{
u.push( v );
dict.erase( v );
}
}
v = temp;
}
}
}
}
return 0;
}
};