-
Notifications
You must be signed in to change notification settings - Fork 277
/
WordLadder.java
96 lines (76 loc) · 2.44 KB
/
WordLadder.java
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
93
94
95
96
class Solution {
// TC: O(n*n)/ O(v+E)
// SC : O(V+E)
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> set = new HashSet<>();
for(String el: wordList){
set.add(el);
}
set.add(beginWord);
Map<String, List<String>> map = new HashMap<>();
buildGraph(map, set);
Set<String> visited = new HashSet<String>();
Queue<String> qu = new LinkedList<>();
qu.offer(beginWord);
int level = 0;
while(!qu.isEmpty()){
int size = qu.size();
while(size-->0){
String head = qu.poll();
if(head.equals(endWord)){
return level+1;
}
if(visited.contains(head)){
continue;
}
for(String connection : map.getOrDefault(head, new ArrayList<>())){
if(!visited.contains(connection)){
qu.offer(connection);
}
}
visited.add(head);
}
level++;
}
if(visited.contains(endWord)){
return level;
} else{
return 0;
}
}
// O(n2)
private void buildGraph(Map<String, List<String>> map, Set<String> wordSet){
for(String el : wordSet){
for(String innerEl : wordSet){
if(el.equals(innerEl)){
continue;
}else {
if(stringsDifferByOne(el, innerEl)){
// el to innerEl
List<String> connections = map.getOrDefault(el, new ArrayList<>());
connections.add(innerEl);
map.put(el, connections);
}
}
}
}
}
private boolean stringsDifferByOne(String a, String b){
if(a.length() !=b.length()){
return false;
} else{
boolean foundOneDifference = false;
for(int i=0;i<a.length();i++){
char aChar = a.charAt(i);
char bChar = b.charAt(i);
if(aChar != bChar){
if(foundOneDifference){
return false;
}
foundOneDifference = true;
}
}
return true;
}
}
}