diff --git a/solutions/java/relative-distance/1/src/main/java/RelativeDistance.java b/solutions/java/relative-distance/1/src/main/java/RelativeDistance.java new file mode 100644 index 00000000..e1c4cbf4 --- /dev/null +++ b/solutions/java/relative-distance/1/src/main/java/RelativeDistance.java @@ -0,0 +1,75 @@ +import java.util.List; +import java.util.*; + +class RelativeDistance { + + Map> familyTree = new HashMap<>(); + + RelativeDistance(Map> familyTree) { + for (Map.Entry> entry : familyTree.entrySet()) { + String parent = entry.getKey(); + List children = entry.getValue(); + + if (!this.familyTree.containsKey(parent)) { + this.familyTree.put(parent, new ArrayList<>()); + } + + for (String child : children) { + if (!this.familyTree.containsKey(child)) { + this.familyTree.put(child, new ArrayList<>()); + } + + this.familyTree.get(parent).add(child); + this.familyTree.get(child).add(parent); + } + + for (int i = 0; i < children.size(); i++) { + for (int j = i + 1; j < children.size(); j++) { + String sibling1 = children.get(i); + String sibling2 = children.get(j); + + this.familyTree.get(sibling1).add(sibling2); + this.familyTree.get(sibling2).add(sibling1); + } + } + } + } + + int degreeOfSeparation(String personA, String personB) { + if (personA.equals(personB)) { + return 0; + } else if (!familyTree.containsKey(personA)) { + return -1; + } else if (!familyTree.containsKey(personB)) { + return -1; + } + + Queue queue = new LinkedList<>(); + Queue distances = new LinkedList<>(); + HashSet visited = new HashSet<>(); + + queue.add(personA); + distances.add(0); + visited.add(personA); + + while (!queue.isEmpty()) { + String currentPerson = queue.poll(); + int currentDistance = distances.poll(); + + if (currentPerson.equals(personB)) { + return currentDistance; + } + + List nachbarn = familyTree.get(currentPerson); + + for (String nachbar : nachbarn) { + if (!visited.contains(nachbar)) { + visited.add(nachbar); + queue.add(nachbar); + distances.add(currentDistance + 1); + } + } + } + return -1; + } +}