Skip to content
Veltoryx Technologies
FreeProblem 107● MediumLeetCode #200 ↗3 min readUpdated 30 October 2026

Number of Islands

Count the number of disconnected islands in a 2D binary grid by sinking land with DFS.

01The problem

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

InputOutputWhy
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]33 distinct connected components of land.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

02How to spot it

  • "Number of connected components in a grid": Whenever you see an unvisited land cell '1', increment island count and launch a DFS to sink all connected '1's into '0's.
  • In-place sinking: Changing '1' to '0' guarantees no cell is visited twice and avoids allocating a separate boolean[][] visited matrix.

03Pseudocode

text
count = 0
for every cell:
  if cell is '1':
    count += 1
    sink(cell) # island -> '0'
return count

04Watch it work

Visualizer · step through the algorithmgrid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]

binary grid

11000
11000
00100
00011

islands found

0

Scan grid row by row: upon finding '1', increment island count and sink entire island to '0'.

Pseudocode

  1. count = 0
  2. for every cell:
  3. if cell is '1':
  4. count += 1
  5. sink(cell) # island -> '0'
  6. return count

Variables

count
0
step 1 / 5

05Step-by-step dry run

We trace the grid:

Land cell foundCurrent countCells sunk by DFSRemaining land
(0, 0)1Sinks (0,0), (0,1), (1,0), (1,1)(2,2), (3,3), (3,4)
(2, 2)2Sinks (2,2) (isolated cell)(3,3), (3,4)
(3, 3)3Sinks (3,3), (3,4)None

Output: 3.

06Java solution

java
public class Solution {
    public static int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        int count = 0;
        int m = grid.length;
        int n = grid[0].length;

        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (grid[r][c] == '1') {
                    count++;
                    sink(grid, r, c);
                }
            }
        }
        return count;
    }

    private static void sink(char[][] grid, int r, int c) {
        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') {
            return;
        }
        grid[r][c] = '0';
        sink(grid, r + 1, c);
        sink(grid, r - 1, c);
        sink(grid, r, c + 1);
        sink(grid, r, c - 1);
    }

    public static void main(String[] args) {
        char[][] grid = {
            {'1','1','0','0','0'},
            {'1','1','0','0','0'},
            {'0','0','1','0','0'},
            {'0','0','0','1','1'}
        };
        System.out.println(numIslands(grid));
    }
}
Expected output
3

07Why it works

Each island is a maximal connected component in the grid graph. By iterating through all cells and triggering a sinking DFS only when encountering '1', the outer loop fires exactly once per island. The DFS then exhausts the entire component, marking every cell '0' so it is never counted again.

08Time and space

  • Time complexity: O(m * n). Every cell is visited at most a constant number of times (once by the nested loop, and once by the DFS).
  • Space complexity: O(m * n) worst-case call stack recursion depth if the entire grid is one giant island.

09Edge cases

  • Grid contains only water ('0'): Returns 0.
  • Grid contains only land ('1'): Returns 1.
  • Checkerboard pattern: Every '1' is an isolated 1-cell island.

10Common mistakes

  • Checking diagonals: Standard problem specifies 4 directions (horizontal and vertical only). Do not check diagonals unless explicitly asked.

11Other approaches

  • Disjoint Set Union (Union-Find): Useful if land cells are added dynamically over time (LeetCode #305).

12In the interview

  • Opening line: "I will iterate through the grid. When I find a '1', I increment the count and launch a DFS that 'sinks' the island by turning all 4-directionally connected '1's into '0's."

13Quiz

Why is changing grid[r][c] from '1' to '0' during DFS helpful?

  • (Recommended) It marks the cell as visited in-place, preventing infinite loops and eliminating the need for an auxiliary visited array
  • It converts land into sea so fish can swim
  • It reduces the time complexity from O(mn) to O(1)
  • It sorts the grid alphabetically

Answer: It marks the cell as visited in-place, preventing infinite loops and eliminating the need for an auxiliary visited array.

14Solve it yourself

Open LeetCode #200 and submit the sinking DFS solution.