04

Shortest Paths DP

Chapter 4 • Advanced

120 min

Shortest Paths DP

Bellman-Ford Algorithm

Find shortest paths from source, handles negative weights.

Algorithm

Relax all edges (V-1) times.

python.js
def bellman_ford(graph, start):
    """
    Bellman-Ford algorithm.
    graph: [(u, v, weight), ...]
    Time: O(V * E), Space: O(V)
    """
    n = len(graph)
    dist = [float('inf')] * n
    dist[start] = 0
    
    # Relax edges V-1 times
    for _ in range(n - 1):
        for u, v, weight in graph:
            if dist[u] != float('inf') and dist[u] + weight < dist[v]:
                dist[v] = dist[u] + weight
    
    # Check for negative cycles
    for u, v, weight in graph:
        if dist[u] != float('inf') and dist[u] + weight < dist[v]:
            return None, True  # Negative cycle detected
    
    return dist, False

Floyd-Warshall (All Pairs Shortest Paths)

python.js
def floyd_warshall(graph):
    """
    All pairs shortest paths.
    graph: adjacency matrix
    Time: O(V³), Space: O(V²)
    """
    n = len(graph)
    dist = [row[:] for row in graph]
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] != float('inf') and dist[k][j] != float('inf'):
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    
    return dist

Practice Problems

  1. Bellman-Ford implementation
  2. Detect negative cycles
  3. All pairs shortest paths
  4. Shortest path with at most K edges