Shortest Path (Dijkstra) - Problem
Given a weighted graph represented as an adjacency list and a source vertex, implement Dijkstra's algorithm to find the shortest path from the source to all other vertices.
The graph is represented as a list of edges where each edge is [from, to, weight]. Return an array where result[i] is the shortest distance from the source to vertex i. If a vertex is unreachable, use -1.
Note: All edge weights are non-negative integers. Vertices are numbered from 0 to n-1.
Input & Output
Example 1 — Basic Graph
$
Input:
n = 4, edges = [[0,1,4],[0,2,2],[1,3,3],[2,3,1]], source = 0
›
Output:
[0,4,2,3]
💡 Note:
From vertex 0: distance to 0 is 0, to 1 is 4 (direct), to 2 is 2 (direct), to 3 is 3 (via 2→3 path costs 2+1=3, better than 1→3 path costs 4+3=7)
Example 2 — Disconnected Vertex
$
Input:
n = 3, edges = [[0,1,5]], source = 0
›
Output:
[0,5,-1]
💡 Note:
From vertex 0: distance to 0 is 0, to 1 is 5 (direct edge), to 2 is -1 (unreachable since no path exists)
Example 3 — Single Vertex
$
Input:
n = 1, edges = [], source = 0
›
Output:
[0]
💡 Note:
Only one vertex exists, distance from vertex 0 to itself is 0
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ edges.length ≤ n × (n-1)
- 0 ≤ source < n
- 0 ≤ weight ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code