Skip to main content
Back to problems
#305
Hard Algorithms

Number of islands ii

Array Hash Table Union-Find
40.5% acceptance
Mar 31, 2026
1986
77
You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's). We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation. Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land. 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_islands2(m: i32, n: i32, positions: Vec<Vec<i32>>) -> Vec<i32> {
    let m = m as usize;
    let n = n as usize;
    let mut parent: Vec<i32> = vec![-1; m * n];
    let mut rank = vec![0u8; m * n];
    let mut count = 0i32;
    let mut result = Vec::with_capacity(positions.len());
    let dirs = [0, 1, 0, -1, 0];

    for pos in &positions {
      let r = pos[0] as usize;
      let c = pos[1] as usize;
      let idx = r * n + c;
      if parent[idx] != -1 {
        result.push(count);
        continue;
      }
      parent[idx] = idx as i32;
      count += 1;

      for d in 0..4 {
        let nr = r as i32 + dirs[d];
        let nc = c as i32 + dirs[d + 1];
        if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 {
          let nidx = nr as usize * n + nc as usize;
          if parent[nidx] != -1 {
            let px = Self::find(&mut parent, idx);
            let py = Self::find(&mut parent, nidx);
            if px != py {
              if rank[px] < rank[py] {
                parent[px] = py as i32;
              } else if rank[px] > rank[py] {
                parent[py] = px as i32;
              } else {
                parent[py] = px as i32;
                rank[px] += 1;
              }
              count -= 1;
            }
          }
        }
      }
      result.push(count);
    }
    result
  }

  fn find(parent: &mut Vec<i32>, mut x: usize) -> usize {
    while parent[x] != x as i32 {
      parent[x] = parent[parent[x] as usize];
      x = parent[x] as usize;
    }
    x
  }
}