Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Traveler {
- public String closest(String[] connections) {
- Set<Integer> visited = new HashSet<>();
- Map<Integer, List<Integer>> adj = new HashMap<>();
- // {"0-1","1-2","2-3","4-5","5-6","3-0"} -> {0: [1, 3], 1: [0, 2], ...}
- for (String c : connections) {
- String[] spl = c.split("-");
- int a = Integer.parseInt(spl[0]);
- int b = Integer.parseInt(spl[1]);
- List<Integer> aAdj = adj.getOrDefault(a, new ArrayList<>());
- List<Integer> bAdj = adj.getOrDefault(b, new ArrayList<>());
- aAdj.add(b);
- bAdj.add(a);
- adj.put(a, aAdj);
- adj.put(b, bAdj);
- }
- LinkedList<Node> q = new LinkedList<>();
- q.add(new Node(0, 0));
- visited.add(0);
- // counts how many nodes are on distance key from the 0-th node
- // {0: [1, 2], 1: [0], 2: [3]}
- // {0: 1, 1: 2, 2: 1}
- // 0 1, 2 3 is on distance 2 from 0
- Map<Integer, Integer> nodesCountOnGivenDistance = new TreeMap<>(); // {3: 100, 5: 200}
- while (!q.isEmpty()) {
- Node current = q.pop();
- for (int neighbor : adj.get(current.index)) {
- if (!visited.contains(neighbor)) {
- Node neighborNode = new Node(neighbor, current.dist + 1);
- q.add(neighborNode); // (1, 1), (7, 1), (8, 1) --> poll 7, 1
- int distanceCount = nodesCountOnGivenDistance.getOrDefault(current.dist + 1, 0);
- nodesCountOnGivenDistance.put(current.dist + 1, distanceCount + 1);
- visited.add(neighbor);
- }
- }
- }
- StringBuilder sb = new StringBuilder();
- for (int count : nodesCountOnGivenDistance.values()) {
- sb.append(String.valueOf(count)).append(",");
- }
- return sb.substring(0, sb.length() - 1);
- }
- public static void main(String[] args) {
- System.out.println(new Traveler().closest(new String[]{"0-1", "0-2", "0-3", "0-10", "0-7", "1-8", "1-6", "2-4", "2-5", "2-8", "3-11", "3-10", "4-8", "8-9", "11-12"}));
- }
- }
- class Node {
- int index, dist;
- public Node(int index, int dist) {
- this.index = index;
- this.dist = dist;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement