AlgoFrames

Connected components and flood fill

A connected component is a group of vertices that can reach each other. Flood fill colours each component, as in counting islands on a grid.

Before you start: Depth-first search.

The idea

A map shows land and water. A program counts the islands by giving every land cell an island number.

Cells that touch side to side get the same number. Cells that touch only at a corner do not.

Intuition

A component is a group of nodes that can reach each other. Nodes in different groups have no path between them.

Scan the nodes in order. A node with no letter starts a new component, and a search from it labels everything it can reach.

Complexity

Each cell goes on the stack once and checks four neighbors: O(rows × columns). The restart curve starts a fresh search from every land cell.

Restarting without seen marks revisits the whole island from each of its cells, about V × V checks. The seen marks prevent that.

The seen marks and the stack hold at most one entry per cell. Space is O(rows × columns).

Pitfalls

Use only up, right, down and left. Cells that touch at a corner are different islands.

Mark a cell as seen when it goes on the stack. Marking it when it comes off lets it go on twice.

Variations

On a graph the same scan finds connected components. Each node is looked at once, so the cost is O(V + E).

Start the fill from the o cells on the border to find cells that stay safe. Every other o is enclosed and can be captured.

Code

Pseudocode

numIslands(grid)
  count ← 0; mark every cell as not seen
  for each cell (r, c) in row-major order
    if (r, c) is land and not seen
      count ← count + 1
      mark (r, c) as seen; push it on a stack
      while the stack is not empty
        take (x, y) from the stack
        for each land neighbor of (x, y) that is not seen
          mark it as seen; push it on the stack
  return count

Python

def num_islands(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    seen = [[False] * cols for _ in range(rows)]
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1 and not seen[r][c]:
                count += 1
                seen[r][c] = True
                stack = [(r, c)]
                while stack:
                    x, y = stack.pop()
                    for dx, dy in ((-1, 0), (0, 1), (1, 0), (0, -1)):
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1 and not seen[nx][ny]:
                            seen[nx][ny] = True
                            stack.append((nx, ny))
    return count

JavaScript

function numIslands(grid) {
  const rows = grid.length;
  const cols = rows ? grid[0].length : 0;
  const seen = Array.from({ length: rows }, () => new Array(cols).fill(false));
  let count = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] !== 1 || seen[r][c]) continue;
      count++;
      seen[r][c] = true;
      const stack = [[r, c]];
      while (stack.length > 0) {
        const [x, y] = stack.pop();
        for (const [dx, dy] of [[-1, 0], [0, 1], [1, 0], [0, -1]]) {
          const nx = x + dx, ny = y + dy;
          if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && grid[nx][ny] === 1 && !seen[nx][ny]) {
            seen[nx][ny] = true;
            stack.push([nx, ny]);
          }
        }
      }
    }
  }
  return count;
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputUndirected graph or grid
OutputA component label per vertex

Practice problems (6)

What is a component? Warm-up

In an undirected graph, nodes u and v are in the same component when a path joins them. Which statement is always true?

Label the components Warm-up

Watch the scan label the graph. A component is a group of nodes joined by edges. Count the groups first, then click the node that shares a component with node 3.

Number of islands Standard

A grid holds 1 for land and 0 for water. An island is a group of land cells joined up, down, left or right. Return the number of islands.

Max area of island Standard

A grid holds 1 for land and 0 for water. An island is a group of land cells joined up, down, left or right. Its area is the number of cells it has.

Return the largest area of any island, or 0 if there is no land.

Count components Standard

An undirected graph has n nodes numbered 0 to n - 1 and a list of edges. Return the number of connected components.

A node with no edges is a component by itself.

Surrounded regions Challenge

A board holds 1 for an O cell and 0 for an X cell. A group of O cells joined up, down, left or right is captured when no O cell of the group is on the border of the board.

Return the board after every captured O has been flipped to 0. Cells that are not captured stay as they are.

Related topics

Next on the path: Cycle detection in undirected and directed graphs