-
Notifications
You must be signed in to change notification settings - Fork 0
/
Word ladder
44 lines (38 loc) · 1.19 KB
/
Word ladder
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
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
queue < pair <string , int> > q ;
map < string , int > m ;
for(int i = 0 ; i < wordList.size() ; i++)
{
m[wordList[i]]++ ;
}
int n = endWord.size() ;
q.push({beginWord , 1}) ;
while(!q.empty())
{
string word = q.front().first;
int dis = q.front().second ;
q.pop() ;
string x = word ;
for(int currind = 0 ; currind < n ; currind++)
{
for(int i = 'a' ; i <= 'z'; i++)
{
x[currind] = i ;
if( m.count(x) > 0 && m[x] != -1 )
{
if(x == endWord)
{
return dis + 1 ;
}
q.push({x , dis + 1 }) ;
m[x] = -1 ;
}
x = word ;
}
}
}
return 0 ;
}
};