743. Network Delay Time (dijkstra

dijkstra

Time complexity: O(Nlog(N) + E),

Space complexity: O(N + E)

  • time: O(ElogE) in the heap implementation, as potentially every edge gets added to the heap.

  • Space Complexity: O(N + E), the size of the graph (O(E)), plus the size of the other objects used (O(N).

class Solution {
    class Pair {
        int node;
        int time;
        Pair(int node, int time) {
            this.node = node;
            this.time = time;
        }
    }
    public int networkDelayTime(int[][] times, int n, int k) { // k: start
        Map<Integer, Set<Pair>> graph = buildGraph(times);
        Queue<Pair> queue = new PriorityQueue<>((a,b) -> a.time - b.time);
        queue.offer(new Pair(k, 0));
        Set<Integer> visited = new HashSet<>();
        
        int res = 0;
        while(!queue.isEmpty()){
            Pair cur = queue.remove();
            int curNode = cur.node;
            int curTime = cur.time;
            if(visited.contains(curNode)) {
                continue;
            }
            visited.add(curNode);
            
            res = curTime;
            n--;
            if(graph.containsKey(curNode)){
                for(Pair next : graph.get(curNode)){
                    queue.add(new Pair(next.node, curTime + next.time));
                }
            }
        }

        return n == 0 ? res : -1;
    }
    private Map<Integer, Set<Pair>> buildGraph(int[][] times) {
        Map<Integer, Set<Pair>> map = new HashMap<>();
        for (int[] time : times) {
            map.computeIfAbsent(time[0], s -> new HashSet<>()).add(new Pair(time[1], time[2]));
            // this q is single way
            //map.computeIfAbsent(edge[1], s -> new HashSet<>()).add(new Pair(edge[0], edge[2]));
        }
        return map;
    }
}

new version

because we use PQ, we poll the smallest path every time, so using visited is reasonable.

Last updated

Was this helpful?