-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-Word Ladder.cpp
More file actions
46 lines (45 loc) · 1.07 KB
/
06-Word Ladder.cpp
File metadata and controls
46 lines (45 loc) · 1.07 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
#include<bits/stdc++.h>
using namespace std;
int ladderLength(string beginWord, string endWord, vector<string> wordList) {
unordered_set<string>s;
for(auto itr:wordList)
{
s.insert(itr);
}
queue<string>q;
int ans=0;
q.push(beginWord);
while(!q.empty())
{
ans++;
vector<string>v;
int n=q.size();
for(int i=0;i<n;i++)
{
string str=q.front();
if(str==endWord){
return ans;
}
for(int j=0;j<str.size();j++)
{
char ch=str[j];
for(int k=0;k<26;k++)
{
str[j]=char(97+k);
if(s.find(str)!=s.end())
{
v.push_back(str);
s.erase(str);
}
}
str[j]=ch;
}
q.pop();
}
for(auto itr:v)
{
q.push(itr);
}
}
return 0;
}