Tensorum

Graph

BFS/DFS, topological sort, shortest paths, MST, union-find, bridges and SCCs — in study order.

DSAAdvanced69 hrs25 patterns · 96 problems
0%
your progress

Core idea

BFS for unweighted shortest paths, Dijkstra for non-negative weights, topological sort for dependencies, DSU for dynamic connectivity, Tarjan for bridges and SCCs.

Reach for it when

  • Grids, dependencies, networks, word ladders
  • Shortest path, connectivity, ordering, cycles
  • Anything with 'states' and 'moves' (state-space BFS)

Template

import heapq
def dijkstra(adj, src):
    dist = {src: 0}
    pq = [(0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist.get(u, float('inf')):
            continue
        for v, w in adj[u]:
            nd = d + w
            if nd < dist.get(v, float(&#39;inf')):
                dist[v] = nd
                heapq.heappush(pq, (nd, v))
    return dist

Complexity

BFS/DFS O(V + E); Dijkstra O(E log V); DSU ~O(α(n)) per op.

Common pitfalls

  • Marking visited on pop instead of push in BFS (duplicates)
  • Dijkstra with negative edges
  • Directed vs undirected cycle detection need different logic

Recognition cues

DFS/BFSDSUTopological SortShortest PathMSTSCCBridgesEulerianGraph DP