mediumGraphsPattern: DFS/BFS

Compute Single-Source Shortest Paths Solution

Problem Statement

You are given a directed, weighted graph represented by `n` vertices, labeled from `0` to `n-1`, and a list of `edges`. Each `edge` is given as a triplet `[u, v, weight]`, indicating a directed edge from vertex `u` to vertex `v` with a non-negative `weight`. You are also given an integer `source`, representing the starting vertex. Your task is to find the shortest distance from the `source` vertex to all other vertices in the graph. The shortest distance to a vertex is the minimum sum of edge weights along any path from the `source` to that vertex. If a vertex is unreachable from the `source`, its distance should be considered `-1`. Return an array `distances` of size `n`, where `distances[i]` is the shortest distance from `source` to vertex `i`.

Examples

Example 1:
Input:n = 4, edges = [[0,1,1], [0,2,4], [1,2,2], [1,3,5], [2,3,1]], source = 0
Output:[0, 1, 3, 4]
Explanation: From source 0: - To vertex 0: Distance is 0. - To vertex 1: Path 0 -> 1 (weight 1). Shortest distance is 1. - To vertex 2: Path 0 -> 1 -> 2 (weight 1 + 2 = 3). Alternative path 0 -> 2 (weight 4). The shortest is 3. - To vertex 3: Path 0 -> 1 -> 2 -> 3 (weight 1 + 2 + 1 = 4). Alternative path 0 -> 2 -> 3 (weight 4 + 1 = 5). The shortest is 4.
Example 2:
Input:n = 4, edges = [[0,1,1], [2,3,10]], source = 0
Output:[0, 1, -1, -1]
Explanation: From source 0: - To vertex 0: Distance is 0. - To vertex 1: Path 0 -> 1 (weight 1). Shortest distance is 1. - Vertices 2 and 3 are unreachable from source 0. Their distances are -1.

Constraints

  • `1 <= n <= 100`
  • `0 <= edges.length <= n * (n - 1)`
  • `0 <= u, v < n`, `u != v`
  • `0 <= weight <= 1000`
  • `0 <= source < n`
Time: O((n + E) log n) Space: O(n + E)
The optimal approach for finding single-source shortest paths in a graph with non-negative edge weights is Dijkstra's algorithm. This algorithm uses a greedy strategy: it continuously extracts the unvisited vertex with the smallest known distance from the source using a min-priority queue and relaxes its neighbors' distances, ensuring that distances are updated efficiently.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

import sys import heapq def solve(): n = int(sys.stdin.readline()) m = int(sys.stdin.readline()) adj = [[] for _ in range(n)] for _ in range(m): u, v, weight = map(int, sys.stdin.readline().split()) adj[u].append((v, weight)) source = int(sys.stdin.readline()) distances = [float('inf')] * n distances[source] = 0 pq = [(0, source)] # (distance, vertex) while pq: dist, u = heapq.heappop(pq) # If we found a shorter path to u already, skip if dist > distances[u]: continue for v, weight in adj[u]: if distances[u] + weight < distances[v]: distances[v] = distances[u] + weight heapq.heappush(pq, (distances[v], v)) # Convert float('inf') to -1 for unreachable vertices result = [] for d in distances: if d == float('inf'): result.append(-1) else: result.append(int(d)) # Ensure integer output print(result) solve()