Logo for ammarahmed.ca
Medium
Oct 04, 2025
#graph
#matrix

200. Number of Islands

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.

Example 1:

1Input: grid = [ 2 ["1","1","1","1","0"], 3 ["1","1","0","1","0"], 4 ["1","1","0","0","0"], 5 ["0","0","0","0","0"] 6] 7Output: 1 8

Example 2:

1Input: grid = [ 2 ["1","1","0","0","0"], 3 ["1","1","0","0","0"], 4 ["0","0","1","0","0"], 5 ["0","0","0","1","1"] 6] 7Output: 3 8

Constraints:

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

          Approach

          To solve this, we can use a depth-first search approach.

          The idea is that we iterate through the grid and when we see a 1 we mark it as a 0, then recursively check all of it's neighbours and do the same until the entire island has been marked as 0. Then, we can increment our islands counter.

          This ensures that we only process every element once because they will be marked as zeros if it's part of a previously processed island.

          Complexity

          Time: O(m * n)

          We iterate through the entire grid once.

          Space: O(1)

          No extra space is created.

          Solution

          1func dfs(grid[][]byte, r, c, rows, cols int) { 2 directions := [][]int{ 3 {0, 1}, 4 {0, -1}, 5 {-1, 0}, 6 {1, 0}, 7 } 8 9 if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') { 10 return 11 } 12 13 grid[r][c] = '0' 14 for _, dir := range directions { 15 dx, dy := dir[0], dir[1] 16 dfs(grid, r + dy, c + dx, rows, cols) 17 } 18 19} 20func numIslands(grid [][]byte) int { 21 ROWS, COLS := len(grid), len(grid[0]) 22 23 islands := 0 24 25 for r, row := range grid { 26 for c, cell := range row { 27 if cell == '1' { 28 // dfs 29 dfs(grid, r, c, ROWS, COLS) 30 islands++ 31 } 32 } 33 } 34 35 return islands 36} 37