IntermediateGraphs

Shortest Path

Dijkstra, 0-1 BFS, Bellman-Ford, and multi-source BFS for path costs

Time: O(E log V) typical
Space: O(V+E)
Pattern Overview

Core Idea

Use appropriate algorithm by weights: BFS for unweighted, 0-1 BFS for {0,1}, Dijkstra for non-negative, Bellman-Ford for negatives.

When to Use

Use to compute distances, minimize costs, or propagate from multiple sources.

General Recognition Cues
General indicators that this pattern might be applicable
  • Min path cost
  • Edge weights present
  • Multiple sources
Pattern Variants & Approaches
Different methodologies and implementations for this pattern
1

Dijkstra

Min-heap relaxations for non-negative weights

When to Use This Variant
  • Positive weights
Use Case
Weighted shortest path
Advantages
  • O(E log V)
  • Efficient
Implementation
import heapq
def dijkstra(n, adj, src):
    dist=[float('inf')]*n; dist[src]=0
    pq=[(0,src)]
    while pq:
        d,u=heapq.heappop(pq)
        if d!=dist[u]: continue
        for v,w in adj[u]:
            nd=d+w
            if nd<dist[v]: dist[v]=nd; heapq.heappush(pq,(nd,v))
    return dist
2

0-1 BFS

Deque where 0 edges push front and 1 edges push back

When to Use This Variant
  • Weights 0 or 1
Use Case
Binary weights
Advantages
  • O(V+E)
  • Simple
Implementation
from collections import deque
def zero_one_bfs(n, adj, src):
    dist=[10**18]*n; dist[src]=0
    dq=deque([src])
    while dq:
        u=dq.popleft()
        for v,w in adj[u]:
            nd=dist[u]+w
            if nd<dist[v]:
                dist[v]=nd
                (dq.appendleft if w==0 else dq.append)(v)
    return dist
3

Bellman-Ford

Relax all edges V-1 times

When to Use This Variant
  • Negative edges
Use Case
Detect negative cycles
Advantages
  • General weights
  • Cycle detection
Implementation
def bellman_ford(n, edges, src):
    INF=10**18; dist=[INF]*n; dist[src]=0
    for _ in range(n-1):
        changed=False
        for u,v,w in edges:
            if dist[u]+w<dist[v]: dist[v]=dist[u]+w; changed=True
        if not changed: break
    # Optional: detect negative cycle
    for u,v,w in edges:
        if dist[u]+w<dist[v]: return None  # negative cycle
    return dist
4

Multi-Source BFS

Push all sources initially

When to Use This Variant
  • Multiple starts
Use Case
Minimum distance to any source
Advantages
  • O(V+E)
  • Easy
Implementation
from collections import deque
def multi_source_bfs(grid, sources):
    R,C=len(grid),len(grid[0]); dist=[[ -1]*C for _ in range(R)]
    q=deque()
    for r,c in sources: dist[r][c]=0; q.append((r,c))
    while q:
        r,c=q.popleft()
        for dr,dc in [(1,0),(-1,0),(0,1),(0,-1)]:
            nr,nc=r+dr,c+dc
            if 0<=nr<R and 0<=nc<C and dist[nr][nc]==-1:
                dist[nr][nc]=dist[r][c]+1
                q.append((nr,nc))
    return dist
Common Pitfalls
Watch out for these common mistakes
  • Using Dijkstra with negative edges
  • Not relaxing edges properly
  • Priority queue stale entries
Code Templates
Compare implementations across different languages
def template(*args, **kwargs):
    # General template placeholder
    pass
Example Problems
Classic LeetCode problems using this pattern
Complexity Analysis
Time Complexity
O(E log V) typical

Depends on algorithm.

Space Complexity
O(V+E)

Graph + queue/heap.

Ready to test your knowledge?

Test your pattern recognition with interactive questions