|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.HashSet; |
| 3 | +import java.util.LinkedList; |
1 | 4 | import java.util.List; |
2 | 5 | import java.util.Map; |
| 6 | +import java.util.Queue; |
3 | 7 |
|
4 | 8 | class RelativeDistance { |
5 | 9 |
|
| 10 | + private final Map<String, HashSet<String>> Graph; |
| 11 | + |
6 | 12 | 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; |
8 | 36 | } |
9 | 37 |
|
10 | 38 | 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; |
12 | 67 | } |
13 | 68 | } |
0 commit comments