Part 17 / Topic 16 of 20
Graphs (BFS and DFS)
A graph is a set of nodes connected by edges - roads between cities, friendships between people, links between pages. The simplest useful representation in Python is an adjacency list: a dict mapping each node to a list of its neighbours. BFS (breadth-first search, using a deque as a FIFO queue) explores ring by ring outward, so it finds the path with the fewest edges first. DFS (depth-first search, often recursive) dives down one path as far as it can before backtracking. Both visit every node and edge once: O(V + E), where V is the number of nodes and E the number of edges.
Think of a road map: BFS is like flood-filling outward from your starting city one ring of neighbouring towns at a time; DFS is like driving down one road as far as it goes before trying the next turn.
| Algorithm | Finds | Time | Data structure used |
|---|---|---|---|
| BFS | fewest edges/hops between two nodes | O(V + E) | deque (FIFO queue) |
| DFS | whether a node is reachable at all; explores deeply | O(V + E) | recursion (or a stack) |
Flagship real-world example: a delivery route between cities. BFS for fewest road hops, ignoring distance:
from collections import deque
ROADS = {
"Pune": [("Mumbai", 150), ("Nashik", 210), ("Delhi", 1500)],
"Mumbai": [("Pune", 150), ("Surat", 280)],
"Nashik": [("Pune", 210), ("Indore", 330)],
"Surat": [("Mumbai", 280), ("Indore", 320), ("Ahmedabad", 280)],
"Indore": [("Nashik", 330), ("Surat", 320), ("Delhi", 820)],
"Ahmedabad": [("Surat", 280), ("Delhi", 930)],
"Delhi": [("Indore", 820), ("Ahmedabad", 930), ("Pune", 1500)],
}
def bfs_fewest_hops(start, goal):
queue = deque([[start]])
visited = {start}
while queue:
path = queue.popleft()
city = path[-1]
if city == goal:
return path
for neighbour, _distance in ROADS.get(city, []):
if neighbour not in visited:
visited.add(neighbour)
queue.append(path + [neighbour])
return None
print(bfs_fewest_hops("Pune", "Delhi")) # ['Pune', 'Delhi'] (1 hop: a direct highway)
Fewest hops is not the same as shortest distance — Pune's direct highway to Delhi is one hop but not the fewest kilometres. Weighted shortest paths get their own topic later in this part, running Dijkstra on this same road map.
Practice: shortest path by number of edges in an unweighted graph (BFS); counting connected groups, or flood-fill on a grid (islands-style problems); reachability and level-by-level spread (rotting-oranges style).
Practice on LeetCode - start here: Flood Fill · Number of Islands · Max Area of Island · Rotting Oranges
Show the full practice list (12 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Island Perimeter | Easy |
| Find if Path Exists in Graph | Easy |
| Keys and Rooms | Medium |
| All Paths From Source to Target | Medium |
| 01 Matrix | Medium |
| Shortest Path in Binary Matrix | Medium |
| Surrounded Regions | Medium |
| Is Graph Bipartite? | Medium |
| Clone Graph | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Pacific Atlantic Water Flow | Medium |
| Snakes and Ladders | Medium |
| Word Ladder | Hard |
Full program: examples/16_graphs_bfs_dfs.py.
Exercise 16: Graphs — count delivery zones (connected components)
Scenario: A city's streets are only partly connected; you need to know how many separate delivery zones exist and which streets are in each.
What to do: Write delivery_zones(roads: dict[str, list[str]]) -> list[list[str]], which runs BFS or DFS from every not-yet-visited street to find each connected group, and returns the groups sorted (sort each group's contents, then sort the list of groups by their first street name).
Starting data:
ROADS = {
"MG Road": ["FC Road"],
"FC Road": ["MG Road"],
"Camp": [],
"Koregaon Park": ["Boat Club Road"],
"Boat Club Road": ["Koregaon Park"],
}
Sample output:
Zones found: 3
['Boat Club Road', 'Koregaon Park']
['Camp']
['FC Road', 'MG Road']
Show the solution to Exercise 16
"""Exercise 16: Graphs - count delivery zones (connected components).
Run: python ex11.py (macOS/Linux: python3 ex11.py)
"""
from collections import deque
ROADS = {
"MG Road": ["FC Road"],
"FC Road": ["MG Road"],
"Camp": [],
"Koregaon Park": ["Boat Club Road"],
"Boat Club Road": ["Koregaon Park"],
}
def delivery_zones(roads: dict[str, list[str]]) -> list[list[str]]:
visited: set[str] = set()
zones: list[list[str]] = []
for start in roads:
if start in visited:
continue
zone = []
queue = deque([start])
visited.add(start)
while queue:
street = queue.popleft()
zone.append(street)
for neighbour in roads.get(street, []):
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
zones.append(sorted(zone))
return sorted(zones, key=lambda zone: zone[0])
def main() -> None:
zones = delivery_zones(ROADS)
print(f"Zones found: {len(zones)}")
for zone in zones:
print(f" {zone}")
if __name__ == "__main__":
main()