intermediate · DFS · grid · connected components · flood fill · stack
Count the separate land masses
Problem
A survey map is a grid: 1 is land and 0 is water. Land cells that touch up, down, left or right belong to the same land mass (diagonals do not connect). Count the land masses.
In the lab the map is given row by row as one list, with its width (■ = land, · = water).
Constraints
- 1 ≤ cells ≤ 30, width 1 to 8 (visualization limit)
- cells are 0 or 1
Examples
map = [[1, 1, 0, 0], [0, 1, 0, 1], [1, 0, 0, 1]] → 3 — The top-left group, the right-hand pair, and the lone bottom-left cell.
Show the solution
Scan and flood with an explicit-stack DFS
Each unvisited land cell met by the scan is the first cell of a new land mass; flooding from it visits exactly that land mass and sinks it so the scan skips it from then on.
Why it is correct
The flood from a cell visits precisely the land cells connected to it: it only steps between touching land cells, and every touching land cell of a visited cell is pushed unless already marked. So each flood sinks one whole land mass. The scan starts a flood exactly when it meets land that no earlier flood reached, i.e. once per land mass.
Complexity
Time O(rows · columns), extra space O(rows · columns) in the worst case for the stack and the copy. The scan visits every cell once; each land cell is pushed once and checks its 4 neighbours once.
For contrast: Give every land cell its own label and repeatedly replace each label by the smallest among its land neighbours until stable; count distinct labels. That costs O((rows · columns)²) time and O(rows · columns) space.
Edge cases
- No land: 0.
- All land: 1.
- Diagonal neighbours are separate land masses.
Common mistakes
- Recursing on large maps and overflowing the call stack; the explicit stack avoids that.
- Marking cells when popped rather than pushed, so a cell can be pushed several times.
- Counting diagonal touches as connected.
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class CountRegions
{
private static readonly (int Dr, int Dc)[] Moves = [(-1, 0), (1, 0), (0, -1), (0, 1)];
/// <summary>Number of 4-connected groups of 1 cells. Scan, and flood each new group with an explicit-stack DFS: O(rows * cols).</summary>
public static int Count(int[][] grid)
{
int rows = grid.Length, cols = grid[0].Length;
var land = grid.Select(row => (int[])row.Clone()).ToArray(); // set to 0 once reached
int regions = 0;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (land[r][c] != 1) continue;
regions++;
land[r][c] = 0;
var stack = new Stack<(int R, int C)>();
stack.Push((r, c));
while (stack.Count > 0)
{
var (cr, cc) = stack.Pop();
foreach (var (dr, dc) in Moves)
{
int nr = cr + dr, nc = cc + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && land[nr][nc] == 1)
{
land[nr][nc] = 0; // mark on push: no cell enters the stack twice
stack.Push((nr, nc));
}
}
}
}
}
return regions;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/CountRegions.cs
from collections.abc import Sequence
MOVES = ((-1, 0), (1, 0), (0, -1), (0, 1))
def count(grid: Sequence[Sequence[int]]) -> int:
"""Number of 4-connected groups of 1 cells. Scan, and flood each new group with an explicit-stack DFS."""
rows, cols = len(grid), len(grid[0])
land = [list(row) for row in grid] # set to 0 once reached
regions = 0
for r in range(rows):
for c in range(cols):
if land[r][c] != 1:
continue
regions += 1
land[r][c] = 0
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for dr, dc in MOVES:
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and land[nr][nc] == 1:
land[nr][nc] = 0 # mark on push: no cell enters the stack twice
stack.append((nr, nc))
return regions
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/count_regions.py
package dev.bekadan.dsa.problems;
import java.util.ArrayDeque;
import java.util.Deque;
public final class CountRegions {
private CountRegions() {
}
private static final int[][] MOVES = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
/** Number of 4-connected groups of 1 cells. Scan, and flood each new group with an explicit-stack DFS. */
public static int count(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int[][] land = new int[rows][]; // set to 0 once reached
for (int r = 0; r < rows; r++) {
land[r] = grid[r].clone();
}
int regions = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (land[r][c] != 1) {
continue;
}
regions++;
land[r][c] = 0;
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[] {r, c});
while (!stack.isEmpty()) {
int[] cell = stack.pop();
for (int[] m : MOVES) {
int nr = cell[0] + m[0];
int nc = cell[1] + m[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && land[nr][nc] == 1) {
land[nr][nc] = 0; // mark on push: no cell enters the stack twice
stack.push(new int[] {nr, nc});
}
}
}
}
}
return regions;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/CountRegions.java
#pragma once
#include <array>
#include <cstddef>
#include <utility>
#include <vector>
namespace bekadan::dsa::problems {
namespace count_regions_detail {
inline constexpr std::array<std::array<int, 2>, 4> kMoves{{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}};
} // namespace count_regions_detail
// Number of 4-connected groups of 1 cells. Scan, and flood each new group with an explicit-stack DFS.
inline int count_regions(const std::vector<std::vector<int>>& grid) {
const int rows = static_cast<int>(grid.size()), cols = static_cast<int>(grid[0].size());
auto land = grid; // set to 0 once reached
const auto at = [&](int r, int c) -> int& { return land[static_cast<std::size_t>(r)][static_cast<std::size_t>(c)]; };
int regions = 0;
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (at(r, c) != 1) continue;
++regions;
at(r, c) = 0;
std::vector<std::pair<int, int>> stack{{r, c}};
while (!stack.empty()) {
const auto [cr, cc] = stack.back();
stack.pop_back();
for (const auto& [dr, dc] : count_regions_detail::kMoves) {
const int nr = cr + dr, nc = cc + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && at(nr, nc) == 1) {
at(nr, nc) = 0; // mark on push: no cell enters the stack twice
stack.emplace_back(nr, nc);
}
}
}
}
}
return regions;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/count_regions.hpp