Skip to main content
Back to problems
#200
Medium Algorithms

Number of islands

Array Depth-First Search Breadth-First Search Union-Find Matrix
63.9% acceptance
Jan 12, 2026
24813
613
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn num_islands(mut grid: Vec<Vec<char>>) -> i32 {
    let mut count = 0;
    let m = grid.len();
    if m == 0 { return 0; }
    let n = grid[0].len();
    
    for i in 0..m {
      for j in 0..n {
        if grid[i][j] == '1' {
          count += 1;
          Self::dfs(&mut grid, i, j, m, n);
        }
      }
    }
    count
  }
  
  fn dfs(grid: &mut Vec<Vec<char>>, i: usize, j: usize, m: usize, n: usize) {
    if i >= m || j >= n || grid[i][j] != '1' {
      return;
    }
    grid[i][j] = '0';
    Self::dfs(grid, i + 1, j, m, n);
    if i > 0 { Self::dfs(grid, i - 1, j, m, n); }
    Self::dfs(grid, i, j + 1, m, n);
    if j > 0 { Self::dfs(grid, i, j - 1, m, n); }
  }
}