Given a weighted Directed Acyclic Graph (DAG) with n nodes and m edges, where each edge is represented as [u, v, w] (a directed edge from u to v with weight w), and a source node src, find the shortest distance from src to all other nodes.
Note: If it is impossible to reach a node from source node, then mark the distance as -1.
Input: V = 4, E = 2, edges = [[0,1,2], [0,2,1]] Output: [0, 2, 1, -1] Explanation: Shortest path from 0 to 1 is 0->1 with edge weight 2. The shortest path from 0 to 2 is 0->2 with edge weight 1. There is no way we can reach 3, so it's -1 for 3.
For a general weighted graph, we can calculate single source shortest distances in O(V + E) time using Bellman–Ford Algorithm. For a graph with no negative weights, we can do better and calculate single source shortest distances in O(E + VLogV) time using Dijkstra's algorithm.
[Expected Approach] Using Topological Sort and Edge Relaxation - O(V + E) Time O(V + E) Space
Can we do even better for Directed Acyclic Graph (DAG)?
For a DAG, we can compute shortest paths in O(V + E) time using topological sorting. Initialize distances (source = 0, others = ∞), get the topological order, and relax edges in that order. Since the graph has no cycles, each edge is processed once, making it the most efficient approach.
We initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.
Following is complete algorithm for finding shortest distances.
Initialize dist[] = {INF, INF, ....} and dist[s] = 0 where s is the source vertex.
Create a topological order of all vertices.
Do following for every vertex u in topological order. ...........Do following for every adjacent vertex v of u ..................if (dist[v] > dist[u] + weight(u, v)) ...........................dist[v] = dist[u] + weight(u, v)
Output
0 2 3 6 1 5
Time Complexity: O(V + E), we perform topological sort and relax each edge once Space Complexity: O(V + E) , for graph storage and distance array