Remove All Ones With Row and Column Flips II - Problem

Imagine you're playing a strategic elimination game on a binary matrix grid! 🎯

You are given an m × n binary matrix where each cell contains either 0 or 1. Your mission is to remove all the 1's from the grid using a special operation.

The Operation: You can select any cell containing 1 at position (i, j), and when you do, all cells in both row i and column j become 0. It's like placing a cross-shaped bomb that clears an entire row and column!

Goal: Find the minimum number of operations needed to turn all 1's into 0's.

Key Insight: This is a clever optimization problem where the order of operations and strategic thinking matter more than brute force!

Input & Output

example_1.py — Basic Grid
$ Input: grid = [[0,1,1,1],[1,1,1,1],[1,1,1,1]]
Output: 3
💡 Note: We can eliminate all 1's in 3 operations: First operation at (1,1) clears row 1 and column 1, leaving [[0,0,1,1],[0,0,0,0],[1,0,1,1]]. Second operation at (2,0) clears row 2 and column 0, leaving [[0,0,1,1],[0,0,0,0],[0,0,0,0]]. Third operation at (0,2) clears the remaining 1's.
example_2.py — Single Cell
$ Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 3
💡 Note: Need 3 operations to clear all 1's. First operation at (0,0) gives [[0,0,0],[0,0,1],[0,1,1]]. Second operation at (1,2) gives [[0,0,0],[0,0,0],[0,1,0]]. Third operation at (2,1) clears all remaining 1's.
example_3.py — Already Clear
$ Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
💡 Note: Grid already contains no 1's, so no operations needed.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 15
  • grid[i][j] is either 0 or 1
  • The grid will always have a valid solution

Visualization

Tap to expand
Remove All Ones With Row and Column Flips II INPUT 3x4 Binary Matrix 0 1 1 1 1 1 1 1 1 1 1 1 Input Array: [[0,1,1,1], [1,1,1,1], [1,1,1,1]] Total 1s: 11 Grid size: 3 x 4 BFS ALGORITHM 1 State Encoding Encode grid as bitmask for BFS states 2 BFS Queue Init Start with initial grid state, depth = 0 3 Explore States For each 1, clear its row and column 4 Find Minimum Return depth when grid becomes all 0s BFS Tree Levels: L0 L1 L1 FINAL RESULT Operation 1: Select (1,1) 0 0 0 0 0 X 0 0 0 0 1 1 Operation 2: Select (2,2) 0 0 0 0 0 0 0 0 0 0 X 0 Output: 2 Min operations All 1s removed - OK Key Insight: BFS explores all possible operation sequences level by level, guaranteeing the minimum number of operations. Each state represents a unique grid configuration encoded as a bitmask. Selecting cell (i,j) clears entire row i and column j in one operation - maximizing coverage. TutorialsPoint - Remove All Ones With Row and Column Flips II | BFS Approach
Asked in
Google 45 Meta 32 Microsoft 28 Amazon 22
43.6K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen