-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path9. Word Ladder
93 lines (75 loc) · 2.32 KB
/
9. 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if(!wordList.contains(endWord)) return 0;
Set<String> beginSet=new HashSet<>();
beginSet.add(beginWord);
Set<String> wordSet=new HashSet<>(wordList);
return bfs(beginSet,endWord,wordSet,1);
}
int bfs(Set<String> beginSet,String endWord,Set<String> wordSet,int distance){
Set<String> reachableSet =new HashSet<>();
wordSet.removeAll(beginSet);
for(String word:beginSet){
for(int pos=0;pos<word.length();pos++){
char[] charArray=word.toCharArray();
for(char c='a';c<='z';c++){
charArray[pos]=c;
String newWord=new String(charArray);
if(wordSet.contains(newWord)){
if(newWord.equals(endWord)){
return distance + 1;
}
reachableSet.add(newWord);
}
}
}
}
distance++;
if(reachableSet.isEmpty()){
return 0;
}
return bfs(reachableSet,endWord,wordSet,distance);
}
}
//Bidirection BFS 100%TC
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if(!wordList.contains(endWord)) return 0;
Set<String> beginSet=new HashSet<>();
Set<String> endSet=new HashSet<>();
Set<String> wordSet=new HashSet<>(wordList);
beginSet.add(beginWord);
endSet.add(endWord);
return bfs(beginSet,endSet,wordSet,1);
}
int bfs(Set<String> beginSet,Set<String> endSet,Set<String> wordSet,int distance){
if(beginSet.size()>endSet.size()){
return bfs(endSet,beginSet,wordSet,distance);
}
Set<String> reachableWords=new HashSet<>();
wordSet.removeAll(beginSet);
for(String word:beginSet){
for(int pos=0;pos<word.length();pos++){
char[] charArray=word.toCharArray();
for(char c='a';c<='z';c++){
charArray[pos]=c;
String newWord=new String(charArray);
if(wordSet.contains(newWord)){
if(endSet.contains(newWord)){
return distance + 1;
}
reachableWords.add(newWord);
//wordSet.remove(newWord);
}
}
}
}
distance++;
if(reachableWords.size()==0){
return 0;
}
else{
return bfs(reachableWords,endSet,wordSet,distance);
}
}
}