DSA/Lesson 8 of 11/6 min read
Graphs
Graph representations, BFS and DFS, topological sort, shortest paths with Dijkstra and Bellman-Ford, MST and union-find.
On this page
Graph
A graph G = (V, E) is a set of vertices and edges.
| Kind | Meaning |
|---|---|
| Directed vs undirected | Edges have a direction or not |
| Weighted vs unweighted | Edges carry a cost or not |
| Cyclic vs acyclic | Contains a cycle or not (DAG = directed acyclic graph) |
| Connected | Path between every pair of vertices (undirected) |
| Strongly connected | Path both ways between every pair (directed) |
| Dense vs sparse | E close to V^2 vs close to V |
Representations
Adjacency List
For each vertex, a list of neighbors. Space O(V + E). Best for sparse graphs, which is most real graphs.
from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u) # undirectedAdjacency Matrix
A V x V grid where M[u][v] is 1 or the weight. Space O(V^2), edge check O(1). Good for dense graphs and Floyd-Warshall.
| List | Matrix | |
|---|---|---|
| Space | O(V + E) | O(V^2) |
| Check edge u-v | O(deg u) | O(1) |
| Iterate neighbors | O(deg u) | O(V) |
Breadth-First Search (BFS)
BFS explores level by level with a queue. In an unweighted graph it finds the shortest path (fewest edges).
from collections import deque
def bfs(graph, src):
dist = {src: 0}
q = deque([src])
while q:
u = q.popleft()
for v in graph[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return distO(V + E) time. Mark nodes visited when enqueued, not when dequeued, or nodes get added many times.
Uses: shortest path in grids, word ladder, rotting oranges (multi-source BFS), level-wise problems.
Depth-First Search (DFS)
DFS goes as deep as possible, then backtracks. Recursion or an explicit stack. O(V + E).
def dfs(u, graph, visited):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v, graph, visited)Uses: connected components, cycle detection, path finding, flood fill (number of islands), topological sort, strongly connected components (Kosaraju, Tarjan), bridges and articulation points.
Cycle detection
- Undirected: during DFS, a visited neighbor that is not the parent means a cycle. Or use union-find.
- Directed: use three colors (white, gray, black). Reaching a gray node (on the current recursion stack) means a back edge, so a cycle.
Bipartite Graph
Vertices split into two sets with every edge crossing between them. Check by 2-coloring with BFS or DFS; a conflict means not bipartite. A graph is bipartite if and only if it has no odd-length cycle.
Topological Sort
A linear order of a DAG where every edge u to v puts u before v. Used for build systems, course schedules, task dependencies.
Kahn's algorithm (BFS)
from collections import deque
def topo_sort(n, edges):
graph = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
graph[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 graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == n else [] # empty means a cycleDFS variant: push a node onto a list after visiting all descendants, then reverse the list.
Shortest paths
| Algorithm | Graph | Time | Notes |
|---|---|---|---|
| BFS | Unweighted | O(V + E) | Fewest edges |
| 0-1 BFS | Weights 0 or 1 | O(V + E) | Deque |
| Dijkstra | Non-negative weights | O((V + E) log V) | Min-heap |
| Bellman-Ford | Negative weights allowed | O(V * E) | Detects negative cycles |
| Floyd-Warshall | All pairs | O(V^3) | DP over intermediate vertex |
Dijkstra's Algorithm
Greedy: always expand the closest unfinished vertex.
import heapq
def dijkstra(graph, src):
dist = {src: 0}
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float("inf")):
continue # stale entry
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return distPitfall: Dijkstra gives wrong answers with negative edge weights, because a finalized node could later get a shorter path.
Bellman-Ford
Relax every edge V - 1 times. If an edge can still be relaxed in round V, there is a negative cycle. Used in distance-vector routing (routing).
Floyd-Warshall
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for every k. Simple triple loop, all pairs.
Minimum Spanning Tree
A subset of edges connecting all vertices with minimum total weight and no cycles (V - 1 edges).
- Kruskal: sort edges by weight; add an edge if it joins two different components (union-find).
O(E log E). - Prim: grow from a start vertex, always adding the cheapest edge leaving the tree (min-heap).
O(E log V).
Kruskal is easier for sparse edge lists; Prim suits dense graphs.
Union-Find
Disjoint Set Union tracks which component each element belongs to.
parent = list(range(n))
rank = [0] * n
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return TrueWith path compression and union by rank, each operation is nearly O(1) (inverse Ackermann). Uses: Kruskal, number of connected components, redundant connection, accounts merge.
Quick revision
- Adjacency list
O(V + E)for sparse graphs; matrixO(V^2)for dense. - BFS gives shortest paths in unweighted graphs; mark visited on enqueue.
- DFS for components, cycles, topological order; gray node means directed cycle.
- Topological sort only on DAGs; Kahn's algorithm detects cycles when output is short.
- Dijkstra needs non-negative weights; Bellman-Ford handles negatives and detects negative cycles.
- MST: Kruskal (sort + union-find) or Prim (heap).
- Union-find with path compression and union by rank is nearly constant time.