Problem 1284

Abstract / Summary

Flip rows and columns to turn all ones to zeros in a binary matrix using the fewest moves possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1284.py

class Solution:
    def minFlips(self, mat: List[List[int]]) -> int:
        m = len(mat[0])
        n = len(mat)
        limit = m * n

        best = 99999
        for mask in range(1 << limit):
            if mask.bit_count() >= best:
                continue

            # deep copy
            grid = []
            for row in mat:
                grid.append(row.copy())

            # try all positions
            for bit in range(limit):
                if (1 << bit) & mask:
                    x = bit %  m
                    y = bit // m

                    grid[y][x] ^= 1
                    if x > 0:     grid[y][x-1] ^= 1
                    if x < m - 1: grid[y][x+1] ^= 1
                    if y > 0:     grid[y-1][x] ^= 1
                    if y < n - 1: grid[y+1][x] ^= 1

            total = 0
            for row in grid:
                total += sum(row)
            if total == 0:
                best = min(best, mask.bit_count())

        return best if best < 99999 else -1
35 lines | 1041 bytes | submitted November 6, 2023 | GitHub   7% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (50k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Breadth First Search
  • Hash Table
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “minimum number of flips” problem for a binary matrix. The goal is to turn every cell to zero by repeatedly selecting a cell and toggling it together with its four orthogonal neighbours. The algorithm explores every possible combination of flip positions using a bitmask representation, tracks the smallest number of flips that achieve an all-zero matrix, and returns that count or -1 when no combination works.

Core Logic

The method begins by extracting the dimensions of the input matrix. The width m is taken from the first row, while the height n is the number of rows. The product limit = m * n represents the total number of cells and therefore the number of bits required to encode a candidate flip set.

m = len(mat[0])
n = len(mat)
limit = m * n

A variable best is initialized with a large sentinel value. It stores the smallest flip count discovered so far. The main loop iterates over every integer mask from 0 up to 2**limit - 1. Each bit in mask indicates whether the corresponding cell is flipped.

best = 99999
for mask in range(1 << limit):
    if mask.bit_count() >= best:
        continue
    ...

The early continue statement discards any mask whose number of set bits is not better than the current best solution, preventing unnecessary work.

Bitmask Enumeration

The enumeration treats the matrix as a flat list ordered row-wise. For a given bit index, the column x is obtained with bit % m and the row y with bit // m. The condition (1 << bit) & mask checks whether the current cell is part of the flip set.

for bit in range(limit):
    if (1 << bit) & mask:
        x = bit %  m
        y = bit // m
        ...

Grid Copying

Because each mask must be evaluated on an independent copy of the original matrix, a deep copy is created before any flips are applied. The copy is built by iterating over the rows and invoking row.copy(), which duplicates the inner lists while preserving the outer list structure.

grid = []
for row in mat:
    grid.append(row.copy())

Flip Simulation

When a cell is selected for flipping, the algorithm toggles the cell itself and any existing orthogonal neighbours. The XOR operator ^= 1 flips a binary value. Boundary checks (x > 0, x < m - 1, y > 0, y < n - 1) ensure that neighbour accesses stay within the matrix limits, thereby handling edge rows and columns gracefully.

grid[y][x] ^= 1
if x > 0:     grid[y][x-1] ^= 1
if x < m - 1: grid[y][x+1] ^= 1
if y > 0:     grid[y-1][x] ^= 1
if y < n - 1: grid[y+1][x] ^= 1

Result Evaluation

After all flips dictated by the current mask have been applied, the algorithm computes the sum of all cells in grid. If the total is zero, the mask successfully turned the entire matrix into zeros. The best variable is then updated with the smaller of its current value and the number of flips used (mask.bit_count()).

total = 0
for row in grid:
    total += sum(row)
if total == 0:
    best = min(best, mask.bit_count())

When the loop finishes, the method returns best if a solution was found; otherwise it returns -1.

return best if best < 99999 else -1

Edge Cases Handled

The implementation naturally accommodates matrices that are already all zeros. In that situation the mask 0 (no flips) yields a total of zero, causing best to become 0. The early pruning condition also works correctly for this case because mask.bit_count() is 0, which is less than the initial sentinel.

When the matrix dimensions are 1 x 1, the neighbour checks become false, and only the selected cell toggles itself. The algorithm still enumerates the two possible masks (0 and 1) and correctly determines whether a single flip is sufficient.

If no combination of flips can clear the matrix, the sentinel value remains unchanged, and the final conditional returns -1. This signals the impossibility of achieving an all-zero state.

Performance Optimizations

The code leverages several built-in language features to reduce overhead. The use of mask.bit_count() provides a fast count of set bits without manual iteration. The early continue based on this count eliminates large swaths of masks that cannot improve the current best solution, dramatically cutting the search space in practice.

Copying the matrix with row.copy() avoids the cost of a full deep copy via generic utilities, keeping the duplication step lightweight. The neighbour toggles are performed in place with XOR, which is both concise and computationally cheap.

By representing the entire flip configuration as a single integer, the algorithm benefits from efficient bitwise operations for both selection testing and counting, allowing the exhaustive search to run as quickly as possible given the combinatorial nature of the problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a flat board made of many squares, where each square can be either a zero or a one. Some squares are one, which is like a light being turned on, and others are zero, which is like a light being turned off. The goal is to make all the lights turn off so the whole board becomes zero.

The code tries a game to fix the lights. It looks at every single square and decides whether to flip the switch there. When a switch is flipped, it changes that square and all the neighbors right next to it. For example, if a square is a one, it becomes a zero, and if it is a zero, it becomes a one.

The code plays this game in many different ways by trying every possible combination of switches. It keeps track of how many times it flips a switch to see if it can clear the board using the smallest number of moves. It starts by guessing that it might take a huge number of moves, and every time it finds a way to clear the board with fewer moves, it remembers that new, better number. After trying all the combinations, the code knows the smallest amount of work needed to turn all the lights off.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5 | μ = 5.00 | σ = 1.82

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
23 links | 13 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 hard
3 solutions   November 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality