743 Network Delay Time

class Solution {
    public int networkDelayTime(int[][] times, int N, int K) {
        Map<Integer, List<int[]>> graph = new HashMap<>();

        for (int[] time : times){
            if (!graph.containsKey(time[0])) graph.put(time[0], new ArrayList<int[]>());
            graph.get(time[0]).add(new int[]{time[1], time[2]});
        }

        Map<Integer, Integer> dist = new HashMap<>();
        for (int i = 1; i <= N; i++){
            dist.put(i, Integer.MAX_VALUE);
        }
        dist.put(K, 0);

        boolean[] seen = new boolean[N + 1];

        while (true){
            int candNode = -1;
            int candDist = Integer.MAX_VALUE;

            for (int d = 1; d <= N; d++){
                if (!seen[d] && dist.get(d) < candDist){
                    candNode = d;
                    candDist = dist.get(d);
                }
            }

            if (candNode == -1) break;
            seen[candNode] = true;

            if (graph.containsKey(candNode))
                for (int[] neighbour : graph.get(candNode)){
                    dist.put(neighbour[0], Math.min(dist.get(neighbour[0]), dist.get(candNode) + neighbour[1]));
                }
        }

        int ans = -1;
        for (int d : dist.values()){
            if (d == Integer.MAX_VALUE) return -1;
            ans = Math.max(ans, d);
        }

        return ans;
    }
}

results matching ""

    No results matching ""