|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.HashSet; |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.Queue; |
| 7 | + |
| 8 | +class RelativeDistance { |
| 9 | + |
| 10 | + private final Map<String, HashSet<String>> graph; |
| 11 | + |
| 12 | + RelativeDistance(Map<String, List<String>> familyTree) { |
| 13 | + final HashMap<String, HashSet<String>> connections = 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 | + connections.putIfAbsent(parent, new HashSet<>()); |
| 20 | + |
| 21 | + for (String child : children) { |
| 22 | + connections.putIfAbsent(child, new HashSet<>()); |
| 23 | + |
| 24 | + connections.get(parent).add(child); |
| 25 | + connections.get(child).add(parent); |
| 26 | + |
| 27 | + for (String sibling : children) { |
| 28 | + if (!sibling.equals(child)) { |
| 29 | + connections.get(child).add(sibling); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + graph = connections; |
| 36 | + } |
| 37 | + |
| 38 | + int degreeOfSeparation(String personA, String personB) { |
| 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; |
| 67 | + } |
| 68 | +} |
0 commit comments