Data Structures & Algorithms · Module 10 · Lesson 11 min read

Graphs & BFS

Vocabulary

  • Vertices (nodes) connected by edges.
  • Directed (one-way, like Twitter follows) or undirected (two-way, like Facebook friends).
  • Weighted edges carry a cost: distance, time, price.

Representing a graph

WayExampleSpaceGood for
Adjacency list{"A": ["B", "C"]}O(V + E)most problems (sparse graphs)
Adjacency matrixm[i][j] = 1O(V²)dense graphs, instant edge checks
Edge list[("A", "B"), ...]O(E)Kruskal's algorithm, input formats

Breadth-first search (BFS)

Explore level by level using a queue:

  1. Put the start in the queue and mark it visited.
  2. Pop a node and add its unvisited neighbours to the queue.
  3. Repeat until the queue is empty.
  • Finds the shortest path in unweighted graphs (fewest edges).
  • O(V + E) time.

Grids are graphs too

Each cell is a node, and its 4 neighbours are edges. BFS finds the shortest route through a maze; counting islands is BFS (or DFS) on each unvisited land cell.

⚠️ Always keep a visited set, or cycles will loop forever.

💡 For weighted shortest paths, use Dijkstra's algorithm: BFS with a heap instead of a queue.

Example

Python
from collections import deque

graph = {
    "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"],
    "D": ["B", "C", "E"], "E": ["D"],
}

def bfs_shortest_path(start, goal):
    queue = deque([[start]])
    visited = {start}
    while queue:
        path = queue.popleft()
        node = path[-1]
        if node == goal:
            return path
        for nxt in graph[node]:
            if nxt not in visited:
                visited.add(nxt)
                queue.append(path + [nxt])
    return None

def count_islands(grid):
    rows, cols, seen, islands = len(grid), len(grid[0]), set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1 and (r, c) not in seen:
                islands += 1
                q = deque([(r, c)]); seen.add((r, c))
                while q:
                    y, x = q.popleft()
                    for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        ny, nx = y + dy, x + dx
                        if 0 <= ny < rows and 0 <= nx < cols \
                                and grid[ny][nx] == 1 and (ny, nx) not in seen:
                            seen.add((ny, nx)); q.append((ny, nx))
    return islands

print(bfs_shortest_path("A", "E"))       # ['A', 'B', 'D', 'E']
print(count_islands([[1, 1, 0, 0],
                     [0, 1, 0, 1],
                     [1, 0, 0, 1]]))     # 3