03. Shortest Path in Directed Acyclic Graph
The problem can be found at the following link: Question Link
My Approach
To find the shortest path in a Directed Acyclic Graph (DAG), we can use a variation of Breadth-First Search (BFS)
algorithm. First, we build a graph representation from the given edges and initialize a vis
array to keep track of the minimum distance from the source node (node 0 in this case) to all other nodes. We'll use a queue to perform the BFS traversal.
Create a
graph
representation using an adjacency list to store the nodes and their corresponding weights.Initialize a queue
q
and avis
array to keep track of minimum distances. Set all distances toINT_MAX
except for the source node, which is set to 0.Push the source node into the queue with distance 0.
While the queue is not empty, perform the following steps:
Dequeue a node and its distance from the queue.
For each neighboring node
next
and its weightw
, update the distance if the path through the current node is shorter than the previously recorded distance.Push the
next
node and its updated distance into the queue.
Convert the
vis
array. If a node has distanceINT_MAX
, set it to-1
, as there is no path from the source to that node.
Time and Auxiliary Space Complexity
Time Complexity:
O(V + E)
time, whereV
is the number of nodes (n) andE
is the number of edges (m).Auxiliary Space Complexity:
O(V)
, whereV
is the number of nodes (n) to store thevis
array and queue.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated