PDSA Interactive Book
Week 4

Graph Algorithms

Vertices, edges, and the two basic ways to explore a graph.

After this chapter you can…
  • store a graph as an adjacency list or matrix and choose between them
  • trace BFS and DFS and say what each one computes
  • use BFS/DFS for reachability, components and fewest-move problems
  • state the O(n + m) bound and why

Graphs: vertices and edges

A graph G = (V, E) is a set of vertices (nodes) and a set of edges joining pairs of vertices. Graphs model road maps, social networks, the web, course prerequisites, circuits and game states. In an undirected graph an edge {u, v} works in both directions; in a directed graph (digraph) an edge (u, v) goes from u to v only. A weighted graph attaches a number (distance, cost) to each edge.

TermMeaning
patha sequence of vertices where consecutive ones are joined by an edge
cyclea path that starts and ends at the same vertex (without reusing edges)
connectedevery vertex can be reached from every other (undirected)
degreenumber of edges at a vertex (in-degree / out-degree for digraphs)
treeconnected graph with no cycle: n vertices, n − 1 edges
DAGdirected acyclic graph
Counting convention

We write n = |V| for vertices and m = |E| for edges. In a simple graph m ≤ n(n−1)/2, so m = O(n²). A graph with m close to n is sparse; with m close to n² it is dense.

Check yourself

A simple undirected graph has 6 vertices. What is the largest number of edges it can have?

Representing a graph

Adjacency matrixAdjacency list
Storagen × n table of 0/1 (or weights): Θ(n²)for each vertex, list of neighbours: Θ(n + m)
Is (u, v) an edge?O(1)O(degree of u)
List all neighbours of uO(n)O(degree of u)
Best fordense graphssparse graphs (most real ones)

We will nearly always use adjacency lists, stored as a dictionary from vertex to list of neighbours. For an undirected edge {u, v}, v appears in u's list and u in v's.

Python · editable
Expected output: {0: [1, 2], 1: [0, 3, 4], 2: [0, 3], 3: [1, 2, 5], 4: [1, 5, 6], 5: [3, 4, 6], 6: [4, 5]} degree of 4: 3
Python · editable
Expected output: [0, 1, 1, 0] [1, 0, 0, 1] [1, 0, 0, 0] [0, 1, 0, 0]
Check yourself

A social network has 10⁶ users, each with about 100 friends. Which representation is practical?

Predict the output

The graph has m undirected edges. What is printed?

adj = {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}
print(sum(len(v) for v in adj.values()))

Breadth-first search (BFS)

Question: which vertices can I reach from vertex s, and what is the fewest number of edges needed to reach each of them?

BFS explores in layers: first s, then everything one edge away, then two edges away, and so on. It keeps a queue of discovered vertices. When it removes a vertex from the queue, it looks at all neighbours and enqueues those it has not seen before.

Python · editable
Expected output: visit order: [0, 1, 2, 3, 4, 5, 6] distances: {0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3} parents: {0: None, 1: 0, 2: 0, 3: 1, 4: 1, 5: 3, 6: 4}
BFS — watch the queue and the layersInteractive
What BFS gives you
  • the set of vertices reachable from s
  • the shortest path length (fewest edges) to each one, in dist
  • the actual shortest paths, by following parent back to s (a BFS tree)

Running time

Each vertex is enqueued once and each adjacency list is scanned once, so BFS takes O(n + m) with adjacency lists — but O(n²) with an adjacency matrix, since scanning a row costs n.

Predict the output

What order does BFS visit the vertices?

from collections import deque
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
seen, q, order = {0}, deque([0]), []
while q:
    u = q.popleft()
    order.append(u)
    for v in adj[u]:
        if v not in seen:
            seen.add(v)
            q.append(v)
print(order)
Check yourself

BFS from s assigns dist[v] = 3 to a vertex. This means…

Check yourself

Which edge-weight situation is BFS suited for?

Depth-first search (DFS)

DFS explores like a person in a maze: go as deep as possible along one path, and when stuck backtrack to the most recent vertex with an unexplored neighbour. It uses recursion (or an explicit stack).

Python · editable
Expected output: [0, 1, 3, 2, 5, 4, 6]
DFS — follow the recursion stackInteractive
Timestamps

Record pre[u] when DFS enters a vertex and post[u] when it leaves, using one global counter. These numbers reveal structure: v is a descendant of u in the DFS tree exactly when pre[u] < pre[v] < post[v] < post[u].

Python · editable
Expected output: ({0: 1, 1: 2, 3: 3, 2: 6}, {3: 4, 1: 5, 2: 7, 0: 8})
BFSDFS
Data structurequeuestack / recursion
Exploreslayer by layerdeep first, then backtracks
Shortest edge-count pathsyesno
Time (adjacency lists)O(n + m)O(n + m)
Predict the output

What order does DFS visit the vertices?

adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
seen, order = set(), []
def go(u):
    seen.add(u)
    order.append(u)
    for v in adj[u]:
        if v not in seen:
            go(v)
go(0)
print(order)
Check yourself

Python raises RecursionError when DFS is run on a path-shaped graph with 10⁵ vertices. Why?

What can we do with BFS and DFS?

Connected components

Run a search from any unvisited vertex, mark everything reached as one component, and repeat. Total time O(n + m).

Python · editable
Expected output: [[0, 1], [2, 3], [4]]

Cycle detection (undirected)

During a search, if we meet a visited vertex that is not the parent we came from, we have found a cycle. A connected graph with m = n − 1 edges is a tree and has no cycle; one with m ≥ n must contain a cycle.

Shortest path in a maze / word ladder

Whenever each move costs one step, model states as vertices and moves as edges, then BFS gives the minimum number of moves.

Python · editable
Expected output: 10

Your turn. Build any graph — drag vertices, add edges, delete things — and run BFS or DFS on your graph. Try a disconnected graph, a long path, a star, a cycle.

Graph lab — build a graph and run BFS / DFS on itInteractive
Check yourself

You want the minimum number of moves for a robot on a grid with obstacles. Best choice?

Check yourself

A connected undirected graph has 10 vertices and 10 edges. It…

Check yourself

Which problems can BFS or DFS solve in O(n + m)?

Chapter challenge — Week 4

…
Check yourself

Which representation makes 'list all neighbours of u' cost only deg(u)?

Predict the output

In the Week 4 graph (code above), what does this print?

# the undirected graph drawn in the visualiser below (vertices 0..6)
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (4, 5), (3, 5), (4, 6), (5, 6)]
n = 7
adj = {v: [] for v in range(n)}
for u, v in edges:
    adj[u].append(v)
    adj[v].append(u)
for v in adj:
    adj[v].sort()

from collections import deque
dist = {0: 0}
q = deque([0])
while q:
    u = q.popleft()
    for v in adj[u]:
        if v not in dist:
            dist[v] = dist[u] + 1
            q.append(v)
print(dist[6])
Predict the output

What is the DFS visit order from vertex 0 (sorted adjacency lists)?

# the undirected graph drawn in the visualiser below (vertices 0..6)
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (4, 5), (3, 5), (4, 6), (5, 6)]
n = 7
adj = {v: [] for v in range(n)}
for u, v in edges:
    adj[u].append(v)
    adj[v].append(u)
for v in adj:
    adj[v].sort()

order, seen = [], set()
def go(u):
    seen.add(u)
    order.append(u)
    for v in adj[u]:
        if v not in seen:
            go(v)
go(0)
print(order)
Put in order

Order the steps of BFS.

Check yourself

A tree has 12 vertices. How many edges does it have?

Check yourself

What is the running time of BFS on a graph stored as adjacency lists?

Check yourself

Pick the true statements.

Check yourself

In an undirected graph, the degrees are 3, 2, 2, 1. How many edges are there?

Practice on LeetCode

BFS, DFS, components and fewest-moves problems.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 10 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Flood Fill ↗EasyDFS/BFS on a grid
Find if Path Exists in Graph ↗Easyreachability
Number of Islands ↗Mediumconnected components on a grid
Number of Provinces ↗Mediumcomponents from an adjacency matrix
Rotting Oranges ↗Mediummulti-source BFS by layers
Shortest Path in Binary Matrix ↗MediumBFS for the fewest steps
Clone Graph ↗Mediumtraversal with a visited map
Binary Tree Level Order Traversal ↗MediumBFS by levels
Is Graph Bipartite? ↗MediumBFS/DFS two-colouring
Word Ladder ↗HardBFS on an implicit graph of words

Key takeaways

  • A graph is vertices + edges; prefer adjacency lists (Θ(n + m)) over matrices (Θ(n²)) unless the graph is dense.
  • BFS: queue, explores by layers, gives fewest-edge distances. DFS: stack/recursion, explores deep then backtracks. Both are O(n + m).
  • Searches answer reachability, connected components, cycle detection, and (BFS) unweighted shortest paths.
  • Sum of degrees is 2m; a tree on n vertices has n − 1 edges.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.