Chapter 11
Graphs & Graph Algorithms
6 topics · 1 sections · beginner-friendly study notes · Updated
A graph G=(V,E) models pairwise relationships.
Choose adjacency list (O(V+E) space) or matrix (O(V^2)); traverse with BFS (shortest path in unweighted graphs) or DFS (cycles, components, topological order); use Dijkstra for non-negative weighted shortest paths.
Graphs appear in routing, dependency resolution and social networks, and are a staple of GATE and interviews.
Maps and GPS, build systems, course prerequisites, web crawling, network flow, social networks.
Graph Representations
A graph G=(V,E) can be stored as an adjacency matrix (V x V, A[u][v]=1 or weight), an adjacency list (for each vertex a list of neighbours), or an edge list. The adjacency list uses O(V+E) space; the matrix uses O(V^2).
In short: Either a big yes/no grid of connections or a per-vertex list of neighbours.
Think about it
The representation determines every complexity bound; GATE asks space/time of operations for each.
Matrix: edge check O(1), iterate neighbours O(V), space O(V^2), good for dense graphs (E near V^2) and Floyd-Warshall.
List: edge check O(deg), iterate neighbours O(deg), total traversal O(V+E), good for sparse graphs.
Undirected graph: matrix is symmetric; each edge appears twice in the list (2E entries).
Max edges: undirected simple V(V-1)/2; directed V(V-1).
Sum of degrees = 2E (handshake lemma); directed: sum of in-degree = sum of out-degree = E. A tree on n vertices has n-1 edges and is connected + acyclic; a connected graph needs at least V-1 edges.
Terms: path, cycle, DAG, connected component, strongly connected component (SCC) in directed graphs, bipartite (2-colourable, no odd cycle), weighted, multigraph, self-loop.
Implicit graphs (grids, word ladders) generate neighbours on demand.
Python: dict of lists / defaultdict(list).
Incidence matrix is V x E. Use 0-indexed integer ids; remember the grid neighbour offsets and bounds checks.
Key points
- Degree: Number of edges at a vertex (in/out for directed).
- DAG: Directed acyclic graph.
- Sparse / dense: E much less than V^2 / E near V^2.
- Bipartite: Vertices split into two sets with edges only between sets.
Read more
Example
CodeBuilding graphs:
from collections import defaultdict
def build_list(n, edges, directed=False):
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
if not directed: g[v].append(u)
return g
def build_weighted(edges, directed=False):
g = defaultdict(list)
for u, v, w in edges:
g[u].append((v, w))
if not directed: g[v].append((u, w))
return g
def build_matrix(n, edges):
m = [[0] * n for _ in range(n)]
for u, v in edges:
m[u][v] = m[v][u] = 1
return m
DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)] # grid neighboursBreadth-First Search (BFS)
BFS explores vertices in increasing distance (number of edges) from the source using a FIFO queue and a visited set. Time O(V+E) with adjacency lists, O(V^2) with a matrix; space O(V).
In short: Spread out like ripples: all neighbours, then neighbours of neighbours.
Think about it
The tool for shortest path with unit weights and level-order problems.
Mark nodes visited when enqueued (not when dequeued) to avoid pushing duplicates.
BFS computes shortest paths in UNWEIGHTED graphs (fewest edges) and yields the BFS tree via parent pointers.
Disconnected graphs: loop over all vertices to cover each component (count components).
Level-by-level processing gives distances; multi-source BFS (enqueue all sources initially) solves rotting oranges, 01-matrix, walls and gates.
0-1 BFS uses a deque for weights 0/1.
Bipartite check: BFS 2-colouring; a conflicting edge means an odd cycle.
Grid shortest path with obstacles: BFS over cells, 4 or 8 neighbours.
Word ladder, minimum knight moves, open-the-lock are implicit-graph BFS.
Space is the maximum frontier size, up to O(V).
Undirected BFS tree edges connect consecutive levels (non-tree edges connect the same or adjacent levels).
Key points
Example
CodeBFS, path, bipartite, multi-source:
from collections import deque
def bfs(g, src):
dist = {src: 0}; parent = {src: None}
q = deque([src])
while q:
u = q.popleft()
for v in g[u]:
if v not in dist: # mark when ENQUEUED
dist[v] = dist[u] + 1
parent[v] = u
q.append(v)
return dist, parent
def shortest_path(g, s, t):
dist, parent = bfs(g, s)
if t not in dist: return []
path = []
while t is not None:
path.append(t); t = parent[t]
return path[::-1]
def is_bipartite(g):
color = {}
for s in range(len(g)):
if s in color: continue
color[s] = 0; q = deque([s])
while q:
u = q.popleft()
for v in g[u]:
if v not in color:
color[v] = 1 - color[u]; q.append(v)
elif color[v] == color[u]:
return False
return True
def rotting_oranges(grid): # multi-source BFS on grid
R, C = len(grid), len(grid[0]); q = deque(); fresh = 0
for r in range(R):
for c in range(C):
if grid[r][c] == 2: q.append((r, c, 0))
elif grid[r][c] == 1: fresh += 1
t = 0
while q:
r, c, t = 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 grid[nr][nc] == 1:
grid[nr][nc] = 2; fresh -= 1; q.append((nr, nc, t + 1))
return t if fresh == 0 else -1Depth-First Search (DFS)
DFS explores as deep as possible along each branch before backtracking, using recursion (call stack) or an explicit stack. Time O(V+E), space O(V) for the stack/visited. It records discovery/finish times that classify edges.
In short: Walk down one path as far as you can, then back up and try the next.
Think about it
Underpins cycle detection, topological sort, SCC and backtracking on graphs.
Edge types in a directed DFS: tree, back (to an ancestor, indicates a cycle), forward (to a descendant), cross (to a finished node in another subtree).
Undirected DFS only has tree and back edges.
Connected components: run DFS from each unvisited vertex; the count of starts is the number of components (flood fill / number of islands on a grid is the same).
Path existence, all paths (with backtracking un-marking), and topological order via reverse finish time all use DFS.
Strongly connected components: Kosaraju (two DFS passes, one on the transpose graph) or Tarjan (low-link), O(V+E).
Articulation points and bridges use discovery times and low values.
Recursion depth up to V: in Python raise the recursion limit or use an explicit stack for 10^5 nodes.
Iterative DFS: push neighbours on a stack, mark visited when popped (or pushed carefully) - visiting order differs from the recursive one.
Different from BFS: DFS does NOT give shortest paths in general.
Key points
Example
CodeDFS and components:
import sys
sys.setrecursionlimit(1_000_000)
def dfs_rec(g, u, vis, order):
vis.add(u); order.append(u)
for v in g[u]:
if v not in vis:
dfs_rec(g, v, vis, order)
def dfs_iter(g, s):
vis, st, order = set(), [s], []
while st:
u = st.pop()
if u in vis: continue
vis.add(u); order.append(u)
for v in reversed(g[u]):
if v not in vis: st.append(v)
return order
def count_components(n, g):
vis, cnt = set(), 0
for s in range(n):
if s not in vis:
cnt += 1; dfs_rec(g, s, vis, [])
return cnt
def num_islands(grid):
R, C = len(grid), len(grid[0]); cnt = 0
def sink(r, c):
if 0 <= r < R and 0 <= c < C and grid[r][c] == '1':
grid[r][c] = '0'
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)): sink(r + dr, c + dc)
for r in range(R):
for c in range(C):
if grid[r][c] == '1': cnt += 1; sink(r, c)
return cntCycle Detection in Graphs
Undirected graph: a cycle exists if DFS/BFS meets a visited vertex that is not the parent of the current vertex (or via Union-Find: an edge joining two vertices already in the same set). Directed graph: a cycle exists iff DFS finds a back edge, i.e. an edge to a vertex currently on the recursion stack (or Kahn topological sort cannot process all vertices).
In short: Undirected: seeing a visited neighbour that is not where you came from. Directed: reaching a node still on your current path.
Think about it
Two different algorithms for directed vs undirected is a classic trap; Course Schedule is a top interview question.
The parent check is essential in undirected graphs because every edge appears in both directions; for multigraphs compare edge ids.
Directed graphs need three states (white unvisited, grey in recursion stack, black done): an edge to a grey node is a back edge.
A plain visited set wrongly flags diamond-shaped DAGs (cross/forward edges to a black node).
Union-Find: for each undirected edge, if find(u) == find(v) then cycle else union: near O(E alpha(V)).
Kahn: count processed vertices; if less than V a cycle exists, and the remaining vertices lie on or behind cycles.
A forest with V vertices and C components has V - C edges; extra edge implies a cycle.
Applications: deadlock detection (wait-for graph), course schedule feasibility, detecting circular imports.
Complexity O(V+E).
Key points
Read more
Example
CodeCycle detection three ways:
def has_cycle_undirected(n, g):
vis = [False] * n
def dfs(u, parent):
vis[u] = True
for v in g[u]:
if not vis[v]:
if dfs(v, u): return True
elif v != parent:
return True
return False
return any(not vis[s] and dfs(s, -1) for s in range(n))
def has_cycle_directed(n, g):
WHITE, GREY, BLACK = 0, 1, 2
color = [WHITE] * n
def dfs(u):
color[u] = GREY
for v in g[u]:
if color[v] == GREY: return True # back edge
if color[v] == WHITE and dfs(v): return True
color[u] = BLACK
return False
return any(color[s] == WHITE and dfs(s) for s in range(n))
class DSU:
def __init__(self, n): self.p = list(range(n)); self.r = [0] * n
def find(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]; x = self.p[x]
return x
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a == b: return False # already connected -> cycle
if self.r[a] < self.r[b]: a, b = b, a
self.p[b] = a; self.r[a] += self.r[a] == self.r[b]
return TrueDijkstra's Algorithm
Dijkstra computes single-source shortest paths in a graph with NON-NEGATIVE edge weights by repeatedly finalizing the unvisited vertex with the smallest tentative distance and relaxing its edges. With a binary heap: O((V+E) log V); with an array: O(V^2).
In short: Always expand the closest not-yet-finalized city and update the distances to its neighbours.
Think about it
The most asked weighted shortest-path algorithm; GATE asks complexity, hand traces and why negative weights fail.
Relax: if dist[u] + w < dist[v] then dist[v] = dist[u] + w and push (dist[v], v).
Python heapq has no decrease-key, so push duplicates and skip stale entries (if d > dist[u]: continue).
Greedy correctness: with non-negative weights, the vertex with minimum tentative distance cannot be improved later.
Negative edges break this (a later negative edge can shorten a finalized path); use Bellman-Ford O(VE) (also detects negative cycles) or reweight (Johnson).
Complexity: each edge relaxed once; heap operations O(log V) (or O(log E)); with Fibonacci heap O(E + V log V).
Dense graph (E ~ V^2): array version O(V^2) can be better.
Reconstruct paths with a parent array.
BFS is the special case of unit weights; 0-1 BFS with a deque is O(V+E).
Dijkstra on grids with costs (minimum effort path, network delay time, cheapest flights with K stops needs Bellman-Ford/BFS by layers).
Undirected graph negative edge = negative cycle.
All-pairs: Floyd-Warshall O(V^3) handles negatives but not negative cycles.
Minimum spanning trees (Prim similar structure, Kruskal with Union-Find) are different problems from shortest paths.
Key points
- Relaxation: Improving a distance estimate via a better path.
- Tentative distance: Best distance found so far.
- Lazy deletion: Skip outdated heap entries instead of decrease-key.
- Bellman-Ford: V-1 rounds of relaxing all edges, a V-th improving round means a negative cycle.
Example
CodeDijkstra and Bellman-Ford:
import heapq
def dijkstra(g, src, n):
INF = float('inf')
dist = [INF] * n; dist[src] = 0
parent = [-1] * n
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: # stale entry
continue
for v, w in g[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd; parent[v] = u
heapq.heappush(pq, (nd, v))
return dist, parent
def bellman_ford(n, edges, src):
dist = [float('inf')] * n; dist[src] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]: dist[v] = dist[u] + w
for u, v, w in edges:
if dist[u] + w < dist[v]: return None # negative cycle
return distTopological Sort & Kahn's Algorithm
A topological order of a DAG lists vertices so that for every edge u -> v, u appears before v. It exists iff the graph is acyclic. Kahn's algorithm repeatedly removes vertices with in-degree 0 using a queue: O(V+E). A DFS-based version outputs vertices in reverse finishing order.
In short: Order tasks so every prerequisite comes before the task that needs it.
Think about it
Dependency ordering is ubiquitous; Kahn doubles as a cycle detector in directed graphs.
Kahn: compute in-degrees, enqueue all zero in-degree vertices, pop u, append to order, decrement in-degree of each neighbour and enqueue when it reaches 0.
If len(order) < V there is a cycle.
Using a min-heap instead of a queue yields the lexicographically smallest order.
A DAG may have many valid orders (a unique order iff the queue never holds more than one vertex, i.
e.
there is a Hamiltonian path).
DFS version: postorder append after exploring all neighbours, then reverse; cycle detection with the grey state.
Applications: build systems, course schedule (I and II), task scheduling, alien dictionary (build edges from adjacent words), longest path in a DAG and shortest path in a DAG in O(V+E) by processing in topological order (works even with negative weights), counting paths, DP on DAG.
Number of topological orders is not polynomial in general.
Disconnected DAGs are fine - all zero in-degree sources start in the queue.
Key points
Example
CodeKahn and DFS topological sort:
from collections import deque
def topo_kahn(n, edges):
g = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges:
g[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 g[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order if len(order) == n else [] # [] -> cycle
def can_finish(num_courses, prerequisites): # [course, prereq]
return len(topo_kahn(num_courses, [(p, c) for c, p in prerequisites])) == num_courses
def topo_dfs(n, g):
vis, order = [0] * n, []
def dfs(u):
vis[u] = 1
for v in g[u]:
if vis[v] == 1: raise ValueError('cycle')
if vis[v] == 0: dfs(v)
vis[u] = 2; order.append(u)
for s in range(n):
if vis[s] == 0: dfs(s)
return order[::-1]Solved examples
Max edges in a simple undirected graph with 10 vertices, and space for adjacency matrix vs list at that density?
Counts
Formula Applied:—Approach note: Directed simple graph max is V(V-1) = 90.
Dijkstra from A on edges A-B 4, A-C 1, C-B 2, B-D 1, C-D 5.
Distances
Formula Applied:—Approach note: Path to D: A -> C -> B -> D.
Directed edges 0->1, 1->2, 2->3, 3->1, 0->4. Detect cycle and give Kahn result.
Cycle and processed nodes
Formula Applied:—Approach note: Unprocessed vertices are on or behind a cycle.
Undirected graph edges: (1-2),(1-3),(2-4). Starting BFS from 1 (enqueue neighbors in ascending order), give visit order.
BFS order
Formula Applied:—Approach note: BFS explores by distance layers; DFS would go deep first.
Real-world applications
Using Graphs & Graph Algorithms in real projects
Maps and GPS, build systems, course prerequisites, web crawling, network flow, social networks.
Common mistakes
❌ Myth: A visited set is enough to detect cycles in directed graphs.
Why this is wrong: A DAG diamond (A->B, A->C, B->D, C->D) revisits D without a cycle.
✅ Verified Truth: Track the recursion stack (grey nodes) or use Kahn.
⚠️ Exam Tip: Undirected: parent check; directed: recursion stack.
❌ Myth: Dijkstra works with negative edge weights if there are no negative cycles.
Why this is wrong: A finalized vertex can later be improved through a negative edge, violating the greedy invariant.
✅ Verified Truth: Use Bellman-Ford (O(VE)) for negative weights.
⚠️ Exam Tip: Always check weight signs in the problem.
❌ Myth: DFS finds the shortest path just like BFS.
Why this is wrong: DFS commits to the first deep path found, which may be long.
✅ Verified Truth: BFS gives fewest edges; Dijkstra for weights.
⚠️ Exam Tip: Pick the algorithm by edge weight type.
Revision notes
A graph G=(V,E) models pairwise relationships. Choose adjacency list (O(V+E) space) or matrix (O(V^2)); traverse with BFS (shortest path in unweighted graphs) or DFS (cycles, components, topological order); use Dijkstra for non-negative weighted shortest paths.
High-Yield Quick Revision Points
- List O(V+E) space; matrix O(V^2) O(1) edge check; sum deg = 2E
- BFS: queue, mark on enqueue, shortest path (unweighted), O(V+E)
- DFS: back edge = cycle (directed); parent check (undirected); components
- Dijkstra: non-negative only, O((V+E) log V), skip stale heap entries; negatives -> Bellman-Ford O(VE)
- Topological: Kahn in-degree queue; processed < V means cycle
Practice questions
BFS time complexity with adjacency list:
Dijkstra with binary heap:
Sum of degrees of an undirected graph with E edges:
Kahn returns fewer than V vertices. This means:
Which is used for shortest path on unweighted graph?
Space of adjacency matrix for V vertices: