forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelativeDistance.java
More file actions
68 lines (54 loc) · 1.97 KB
/
Copy pathRelativeDistance.java
File metadata and controls
68 lines (54 loc) · 1.97 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class RelativeDistance {
private final Map<String, HashSet<String>> graph;
RelativeDistance(Map<String, List<String>> familyTree) {
final HashMap<String, HashSet<String>> connections = new HashMap<>();
for (Map.Entry<String, List<String>> entry : familyTree.entrySet()) {
String parent = entry.getKey();
List<String> children = entry.getValue();
connections.putIfAbsent(parent, new HashSet<>());
for (String child : children) {
connections.putIfAbsent(child, new HashSet<>());
connections.get(parent).add(child);
connections.get(child).add(parent);
for (String sibling : children) {
if (!sibling.equals(child)) {
connections.get(child).add(sibling);
}
}
}
}
graph = connections;
}
int degreeOfSeparation(String personA, String personB) {
if (!graph.containsKey(personA) || !graph.containsKey(personB)) {
return -1;
}
Queue<String> queue = new LinkedList<>();
Map<String, Integer> distances = new HashMap<>() {
{
put(personA, 0);
}
};
queue.add(personA);
while (!queue.isEmpty()) {
String current = queue.poll();
int currentDistance = distances.get(current);
for (String relative : graph.get(current)) {
if (!distances.containsKey(relative)) {
if (relative.equals(personB)) {
return currentDistance + 1;
}
distances.put(relative, currentDistance + 1);
queue.add(relative);
}
}
}
return -1;
}
}