-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathWordLadderI.cpp
More file actions
62 lines (49 loc) · 1.1 KB
/
WordLadderI.cpp
File metadata and controls
62 lines (49 loc) · 1.1 KB
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
59
60
61
62
bool isadjacent(string s,string t)
{
int c=0;
int n=s.size();
for(int i=0;i<n;i++)
{
if(s[i]!=t[i])
c++;
if(c>1)
return false;
}
return c==1? true: false;
}
struct node
{
string word;
int len;
};
int Solution::ladderLength(string start, string target, vector<string> &dict) {
if(start==target)
return 1;
set <string> D;
for(int i=0;i<dict.size();i++){
string x=dict[i];
D.insert(x);
}
queue<node> q;
node item = {start, 1};
q.push(item);
while (!q.empty())
{
node curr = q.front();
q.pop();
for (set<string>::iterator it = D.begin(); it != D.end(); it++)
{
string temp = *it;
if (isadjacent(curr.word, temp))
{
item.word = temp;
item.len = curr.len + 1;
q.push(item);
D.erase(temp);
if (temp == target)
return item.len;
}
}
}
return 0;
}