sagelearnai

Graphs (BFS, DFS, Topological Sort)

Signal: grids of cells, networks of cities, courses with prerequisites, word transformations, "connected", "reachable", "shortest number of steps", "order respecting dependencies".

Core idea: model the problem as nodes and edges, then pick the traversal:

NeedUse
Visit everything connected / count componentsDFS or BFS
Shortest path in an unweighted graph (min steps)BFS (the first time you reach a node is via a shortest path)
Spreading from many sources at once (rot, fire, distance to nearest X)Multi-source BFS
Ordering with dependencies, cycle detection in a directed graphTopological sort (Kahn's BFS or DFS colors)
Weighted shortest pathsDijkstra (heap), with non-negative weights

Templates

python
from collections import deque

# Grid BFS (4-directional)
def bfs(grid, sr, sc):
    R, C = len(grid), len(grid[0])
    q, seen = deque([(sr, sc)]), {(sr, sc)}
    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 (nr, nc) not in seen and grid[nr][nc] == 1:
                seen.add((nr, nc)); q.append((nr, nc))

# Kahn's topological sort
def topo(n, edges):                    # edges: u -> v means u before v
    adj = [[] for _ in range(n)]; indeg = [0] * n
    for u, v in edges: adj[u].append(v); indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0); order = []
    while q:
        u = q.popleft(); order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0: q.append(v)
    return order if len(order) == n else None   # None → cycle
Mark visited when you enqueue, not when you dequeue

Otherwise the same node can be enqueued many times, which blows up time and memory on dense graphs and grids.

Problems

  1. Number of Islands (Medium): Flood-fill each unvisited land cell
  2. Max Area of Island (Medium): Flood fill returning the size
  3. Clone Graph (Medium): Hash map original → clone doubles as the visited set
  4. Rotting Oranges (Medium): Multi-source BFS, one level per minute
  5. 01 Matrix (Medium): Multi-source BFS starting from every 0 at once
  6. Surrounded Regions (Medium): Mark O's reachable from the border as safe; flip everything else
  7. Pacific Atlantic Water Flow (Medium): Reverse flow: BFS uphill from each ocean's border
  8. Course Schedule (Medium): Topological sort — possible iff no cycle
  9. Course Schedule II (Medium): Kahn's algorithm: repeatedly take courses with in-degree 0
  10. Graph Valid Tree (Medium): A tree has exactly n−1 edges AND is connected (equivalently: acyclic)
  11. Network Delay Time (Medium): Dijkstra from k; answer is the largest shortest distance
  12. Cheapest Flights Within K Stops (Medium): Bellman-Ford limited to k+1 rounds (copy the array each round)
  13. Min Cost to Connect All Points (Medium): Minimum spanning tree on the complete graph: dense Prim in O(n²)
  14. Word Ladder (Hard): BFS over words; neighbors via wildcard patterns
  15. Reconstruct Itinerary (Hard): Eulerian path with Hierholzer: DFS consuming edges in lexical order, emit on backtrack
  16. Swim in Rising Water (Hard): Minimax path: Dijkstra on max elevation seen so far
  17. Flood Fill (Easy): DFS/BFS from the start pixel over same-colored 4-neighbors
  18. Find if Path Exists in Graph (Easy): Union all edges, compare roots
  19. Keys and Rooms (Medium): Reachability from room 0: DFS and count visited
  20. All Paths From Source to Target (Medium): DAG → DFS with a path stack, no visited set needed
  21. Shortest Path in Binary Matrix (Medium): BFS over 8 directions; path length counts cells
  22. Is Graph Bipartite? (Medium): 2-color each component with BFS; a same-colored edge means an odd cycle
  23. Path With Minimum Effort (Medium): Dijkstra where a path's cost is its max edge (minimax path)
  24. Minimum Height Trees (Medium): Peel leaves layer by layer; the last 1–2 nodes are the centers
  25. Word Ladder II (Hard): BFS by layers recording parents, then backtrack all shortest paths from end
  26. Shortest Bridge (Medium): DFS to collect island A, then multi-source BFS outward until hitting island B
  27. Critical Connections in a Network (Hard): Tarjan's bridges: edge (u,v) is a bridge iff low[v] > disc[u]
  28. Alien Dictionary (Hard): First differing char of adjacent words gives an edge; topological sort; watch the prefix trap