-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadder.java
More file actions
35 lines (29 loc) · 1.07 KB
/
WordLadder.java
File metadata and controls
35 lines (29 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
class WordLadder{
public static int ladderLength(String s, String d, Set<String> dict){
if(dict.size()==0) return 0;
Queue<String> wordq=new LinkedList<String>();
Queue<Integer> distanceq=new LinkedList<Integer>();
dict.add(d);
wordq.add(s);
distanceq.add(1);
while(!wordq.isEmpty()){
String currWord=wordq.poll();
Integer currDistance=distanceq.poll();
if(currWord.equals(d))
return currDistance;
for(int i=0;i<currWord.length();i++){
char[] currWordArray=currWord.toCharArray();
for(char c='a';c<='z';c++){
currWordArray[i]=c;
String newWord=new String(currWordArray);
if(dict.contains(newWord)){
wordq.add(newWord);
distanceq.add(currDistance+1);
dict.remove(newWord);
}
}
}
}
return 0;
}
}