Skip to main content
Back to problems
#2174
Medium Algorithms

Remove all ones with row and column flips ii

Array Bit Manipulation Breadth-First Search Matrix
67.3% acceptance
Mar 31, 2026
94
24

No description available.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn remove_ones(grid: Vec<Vec<i32>>) -> i32 {
    let m = grid.len();
    let n = grid[0].len();
    
    // Encode grid state as bitmask (m*n <= 15 cells)
    let mut state = 0u32;
    for i in 0..m {
      for j in 0..n {
        if grid[i][j] == 1 {
          state |= 1 << (i * n + j);
        }
      }
    }
    
    if state == 0 {
      return 0;
    }
    
    // Precompute the effect of choosing cell (i,j): clear row i and column j
    let mut effects = vec![vec![0u32; n]; m];
    for i in 0..m {
      for j in 0..n {
        let mut mask = 0u32;
        for jj in 0..n {
          mask |= 1 << (i * n + jj);
        }
        for ii in 0..m {
          mask |= 1 << (ii * n + j);
        }
        effects[i][j] = mask;
      }
    }
    
    // BFS on states
    use std::collections::HashMap;
    let mut dp: HashMap<u32, i32> = HashMap::new();
    dp.insert(state, 0);
    let mut queue = std::collections::VecDeque::new();
    queue.push_back(state);
    
    while let Some(s) = queue.pop_front() {
      let cost = dp[&s];
      if s == 0 {
        return cost;
      }
      for i in 0..m {
        for j in 0..n {
          if s & (1 << (i * n + j)) != 0 {
            let ns = s & !effects[i][j];
            if !dp.contains_key(&ns) {
              dp.insert(ns, cost + 1);
              queue.push_back(ns);
            }
          }
        }
      }
    }
    
    -1
  }
}