forked from iiitu-force/hacktoberfest22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Word Ladder.cpp
37 lines (31 loc) · 1.21 KB
/
Word Ladder.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
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> set = new HashSet<>(wordList);
if(!set.contains(endWord)) return 0;
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
Set<String> visited = new HashSet<>();
queue.add(beginWord);
int changes = 1;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
String word = queue.poll();
if(word.equals(endWord)) return changes;
for(int j = 0; j < word.length(); j++){
for(int k = 'a'; k <= 'z'; k++){
char arr[] = word.toCharArray();
arr[j] = (char) k;
String str = new String(arr);
if(set.contains(str) && !visited.contains(str)){
queue.add(str);
visited.add(str);
}
}
}
}
++changes;
}
return 0;
}
}