Skip to content

Commit 0aab880

Browse files
committed
Add implementation
1 parent bdb27f4 commit 0aab880

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed
Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,68 @@
1+
import java.util.HashMap;
2+
import java.util.HashSet;
3+
import java.util.LinkedList;
14
import java.util.List;
25
import java.util.Map;
6+
import java.util.Queue;
37

48
class RelativeDistance {
59

10+
private final Map<String, HashSet<String>> Graph;
11+
612
RelativeDistance(Map<String, List<String>> familyTree) {
7-
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
13+
final HashMap<String, HashSet<String>> graph = new HashMap<>();
14+
15+
for (Map.Entry<String, List<String>> entry : familyTree.entrySet()) {
16+
String parent = entry.getKey();
17+
List<String> children = entry.getValue();
18+
19+
graph.putIfAbsent(parent, new HashSet<>());
20+
21+
for (String child : children) {
22+
graph.putIfAbsent(child, new HashSet<>());
23+
24+
graph.get(parent).add(child);
25+
graph.get(child).add(parent);
26+
27+
for (String sibling : children) {
28+
if (!sibling.equals(child)) {
29+
graph.get(child).add(sibling);
30+
}
31+
}
32+
}
33+
}
34+
35+
Graph = graph;
836
}
937

1038
int degreeOfSeparation(String personA, String personB) {
11-
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
39+
if (!Graph.containsKey(personA) || !Graph.containsKey(personB)) {
40+
return -1;
41+
}
42+
43+
Queue<String> queue = new LinkedList<>();
44+
Map<String, Integer> distances = new HashMap<>() {
45+
{
46+
put(personA, 0);
47+
}
48+
};
49+
queue.add(personA);
50+
51+
while (!queue.isEmpty()) {
52+
String current = queue.poll();
53+
int currentDistance = distances.get(current);
54+
55+
for (String relative : Graph.get(current)) {
56+
if (!distances.containsKey(relative)) {
57+
if (relative.equals(personB)) {
58+
return currentDistance + 1;
59+
}
60+
distances.put(relative, currentDistance + 1);
61+
queue.add(relative);
62+
}
63+
}
64+
}
65+
66+
return -1;
1267
}
1368
}

0 commit comments

Comments
 (0)