Given a weighted undirected graph with n vertices (labeled 0 to n-1) and a list of edges where edges[i] = [u, v, weight], find the shortest distance from vertex 0 to every other vertex using Dijkstra's algorithm.
Return an array dist of length n where dist[i] is the shortest distance from vertex 0 to vertex i. All vertices are reachable.
Example
Input: n = 5, edges = [[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5],[3,4,3]] Output: [0, 3, 1, 4, 7] Explanation: - 0 → 0: distance 0 - 0 → 2 → 1: distance 1 + 2 = 3 - 0 → 2: distance 1 - 0 → 2 → 1 → 3: distance 1 + 2 + 1 = 4 - 0 → 2 → 1 → 3 → 4: distance 1 + 2 + 1 + 3 = 7
Constraints
2 <= n <= 10001 <= edges.length <= 50000 <= u, v < n1 <= weight <= 1000- The graph is connected.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check