The Indian Engineer

Problem 743 Network Delay Time

Posted on Last edited 3 mins

Dijkstras Graph Shortest-Path

Problem Statement

Link - Problem 743

Question

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.

We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

Example 1

image1

Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2

Example 2

Input: times = [[1,2,1]], n = 2, k = 1
Output: 1

Example 3

Input: times = [[1,2,1]], n = 2, k = 2
Output: -1

Constraints

Solution

class Solution {
public:

    vector<int> dijkstras(int src,vector<vector<pair<int,int>>>&adj,int V){
        vector<int>dist(V+1,INT_MAX);
        dist[src] = 0;
        priority_queue<pair<int,int>,vector<pair<int,int>>, greater<pair<int,int>>>pq;
        pq.push({0,src});
        while(!pq.empty()){
            int node = pq.top().second;
            int wt = pq.top().first;
            pq.pop();
            for(auto it:adj[node]){
                if(wt + it.second < dist[it.first]){
                    dist[it.first] = wt + it.second;
                    pq.push({dist[it.first], it.first});
                }
            }
        }
        return dist;
    }
    int networkDelayTime(vector<vector<int>>& times, int n, int k) {
        vector<vector<pair<int,int>>>adj(n+1);
        for(int i = 0; i<times.size();i++){
            auto u = times[i];
            adj[u[0]].push_back({u[1],u[2]});
        }

        vector<int>dist = dijkstras(k,adj,n);
        dist[0] = INT_MIN; // becuz numbered from 1 to n
        int maxi = INT_MIN;
        for(auto it:dist){
            maxi = max(maxi,it);
        }

        if(maxi==INT_MAX)
            return -1;
        else
            return maxi;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Dijsktra O(ElogV) O(V+E)

Explanation

1. Intuition

2. Implementation