Graphs & Grids

Data Structures & Algorithms · Graphs & Disjoint Sets · Advanced · 16 min

Cities connected by roads: explore them with BFS/DFS.

Ink dropped on a map. With BFS the ink spreads in rings, one road away, then two, then three. With DFS a single ant runs as far as it can down one road, and only turns back at a dead end. On a grid of islands, you pour ink on each new piece of land and it soaks the whole island at once.

The idea in everyday words

A graph is a map of cities (nodes) and roads (edges). Social networks (people + friendships), Google Maps, and the internet are all graphs. A grid (like a chessboard) is a graph where each cell connects to its neighbours up, down, left and right.

Storing a graph

Adjacency list (most common):

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

Always keep a visited set so you don't walk in circles forever.

Number of islands (grid DFS)

Grid of "1" (land) and "0" (water). Scan every cell. When you find unvisited land: count += 1, then "flood fill": DFS to mark all connected land as visited. Each island is counted exactly once.

Step by step

  1. Scan:

    Find first '1' at (0,0). islands = 1.

  2. Flood fill:

    DFS sinks all connected 1s (mark them visited).

  3. Keep scanning:

    Skip visited cells. Find a new '1' → islands = 2.

  4. Done:

    Every land cell visited once → O(rows × cols).

Code example

def bfs(graph, start):
    from collections import deque
    visited, q, order = {start}, deque([start]), []
    while q:
        node = q.popleft()
        order.append(node)
        for nb in graph[node]:
            if nb not in visited:
                visited.add(nb)
                q.append(nb)
    return order

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(bfs(graph, "A"))

Complexity

  • Time: O(V + E)
  • Space: O(V)

Interview tips

  • Number of Islands, Clone Graph, Course Schedule: must-know graph questions.

  • Say out loud whether the graph is directed and weighted.

  • For grids, write a directions list: [(1,0),(-1,0),(0,1),(0,-1)].

Challenge: Count the Islands

Given a grid of 1 (land) and 0 (water), return the number of islands (land connected up/down/left/right).

Example: [[1,1,0],[0,1,0],[0,0,1]] → 2

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Graphs & Disjoint Sets

Previous: Tries (Prefix Trees) · Next: Union-Find (Disjoint Sets)