Problem
There is a directed weighted graph that consists of n
nodes numbered from 0
to n - 1
. The edges of the graph are initially represented by the given array edges
where edges[i] = [fromi, toi, edgeCosti]
meaning that there is an edge from fromi
to toi
with the cost edgeCosti
.
Implement the Graph
class:
Graph(int n, int[][] edges)
initializes the object withn
nodes and the given edges.addEdge(int[] edge)
adds an edge to the list of edges whereedge = [from, to, edgeCost]
. It is guaranteed that there is no edge between the two nodes before adding this one.int shortestPath(int node1, int node2)
returns the minimum cost of a path fromnode1
tonode2
. If no path exists, return-1
. The cost of a path is the sum of the costs of the edges in the path.
Examples
Example 1:
|
|
Solution
Method 1 – Dijkstra’s Algorithm with Adjacency List
Intuition
To efficiently find the shortest path in a directed weighted graph, we use Dijkstra’s algorithm. This algorithm explores nodes in order of increasing path cost, always expanding the least costly path first. By maintaining an adjacency list, we can quickly access neighbors and update path costs as we traverse the graph.
Approach
- Store the graph as an adjacency list, where each node maps to a list of (neighbor, cost) pairs.
- For shortestPath, use a min-heap to always expand the node with the lowest current cost.
- Track the minimum cost to reach each node using a distance array or map.
- When adding an edge, update the adjacency list.
- If the destination is reached, return the cost; if not reachable, return -1.
Complexity
- ⏰ Time complexity:
O(E log V)
, where E is the number of edges and V is the number of nodes, due to heap operations in Dijkstra’s algorithm. - 🧺 Space complexity:
O(E + V)
, for storing the adjacency list and heap.
Code
|
|
|
|
|
|