##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1284.html

# 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix (Hard)

Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.

Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.

Binary matrix is a matrix with all cells equal to 0 or 1 only.

Zero matrix is a matrix with all cells equal to 0.

Example 1:

Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

Example 2:

Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We don't need to change it.

Example 3:

Input: mat = [[1,1,1],[1,0,1],[0,0,0]]
Output: 6

Example 4:

Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can't be a zero matrix

Constraints:

• m == mat.length
• n == mat[0].length
• 1 <= m <= 3
• 1 <= n <= 3
• mat[i][j] is 0 or 1.

Related Topics:
Breadth-first Search

## Solution 1. Bit vector + BFS

// OJ: https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/
// Time: O(MN * 2^(MN))
// Space: O(2^(MN))
class Solution {
public:
int minFlips(vector<vector<int>>& A) {
int start = 0, M = A.size(), N = A[0].size(), step = 0, dirs[5] = {1,0,-1,0,1};
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
start |= (A[i][j] << (i * 3 + j));
}
}
queue<int> q;
unordered_set<int> s;
q.push(start);
s.insert(start);
while (q.size()) {
int cnt = q.size();
while (cnt--) {
int state = q.front();
q.pop();
if (state == 0) return step;
for (int i = 0; i < 9; ++i) {
int next = state, r = i / 3, c = i % 3;
next ^= (1 << (r * 3 + c));
for (int j = 0; j < 4; ++j) {
int x = r + dirs[j], y = c + dirs[j + 1];
if (x < 0 || x >= M || y < 0 || y >= N) continue;
next ^= (1 << (x * 3 + y));
}
if (s.count(next) == 0) {
q.push(next);
s.insert(next);
}
}
}
++step;
}
return -1;
}
};
• class Solution {
public int minFlips(int[][] mat) {
int rows = mat.length, columns = mat[0].length;
int[][] zeroMatrix = new int[rows][columns];
String zeroMatrixStr = matrixToString(zeroMatrix);
final int WHITE = 0;
final int GRAY = 1;
final int BLACK = 2;
Map<String, Integer> colorMap = new HashMap<String, Integer>();
Queue<int[][]> queue = new LinkedList<int[][]>();
queue.offer(mat);
Queue<Integer> flipsQueue = new LinkedList<Integer>();
flipsQueue.offer(0);
String matStr = matrixToString(mat);
colorMap.put(matStr, GRAY);
while (!queue.isEmpty()) {
int[][] curMatrix = queue.poll();
int flip = flipsQueue.poll();
String curStr = matrixToString(curMatrix);
if (zeroMatrixStr.equals(curStr))
return flip;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int[][] flipMatrix = flip(curMatrix, i, j);
String flipStr = matrixToString(flipMatrix);
int color = colorMap.getOrDefault(flipStr, WHITE);
if (color == WHITE) {
queue.offer(flipMatrix);
flipsQueue.offer(flip + 1);
colorMap.put(flipStr, GRAY);
}
}
}
colorMap.put(curStr, BLACK);
}
return -1;
}

public String matrixToString(int[][] mat) {
String str = "[";
int rows = mat.length;
for (int i = 0; i < rows; i++) {
int[] row = mat[i];
String rowStr = Arrays.toString(row);
if (i > 0)
str += ", ";
str += rowStr;
}
str += "]";
return str;
}

public int[][] flip(int[][] mat, int row, int column) {
int rows = mat.length, columns = mat[0].length;
int[][] flipMat = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
flipMat[i][j] = mat[i][j];
}
flipMat[row][column] = 1 - flipMat[row][column];
if (row > 0)
flipMat[row - 1][column] = 1 - flipMat[row - 1][column];
if (row < rows - 1)
flipMat[row + 1][column] = 1 - flipMat[row + 1][column];
if (column > 0)
flipMat[row][column - 1] = 1 - flipMat[row][column - 1];
if (column < columns - 1)
flipMat[row][column + 1] = 1 - flipMat[row][column + 1];
return flipMat;
}
}

############

class Solution {
public int minFlips(int[][] mat) {
int m = mat.length, n = mat[0].length;
int state = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 1) {
state |= 1 << (i * n + j);
}
}
}
Deque<Integer> q = new ArrayDeque<>();
q.offer(state);
Set<Integer> vis = new HashSet<>();
vis.add(state);
int ans = 0;
int[] dirs = {0, -1, 0, 1, 0, 0};
while (!q.isEmpty()) {
for (int t = q.size(); t > 0; --t) {
state = q.poll();
if (state == 0) {
return ans;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int nxt = state;
for (int k = 0; k < 5; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n) {
continue;
}
if ((nxt & (1 << (x * n + y))) != 0) {
nxt -= 1 << (x * n + y);
} else {
nxt |= 1 << (x * n + y);
}
}
if (!vis.contains(nxt)) {
vis.add(nxt);
q.offer(nxt);
}
}
}
}
++ans;
}
return -1;
}
}

• // OJ: https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/
// Time: O(MN * 2^(MN))
// Space: O(2^(MN))
class Solution {
public:
int minFlips(vector<vector<int>>& A) {
int M = A.size(), N = A[0].size(), init = 0, step = 0, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) init |= A[i][j] << (i * N + j);
}
queue<int> q{ {init} };
unordered_set<int> seen{init};
auto flip = [&](int &state, int x, int y) { state ^= 1 << (x * N + y); };
while (q.size()) {
int cnt = q.size();
while (cnt--) {
int u = q.front();
q.pop();
if (u == 0) return step;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
int v = u;
flip(v, i, j);
for (auto &[dx, dy] : dirs) {
int a = i + dx, b = j + dy;
if (a < 0 || b < 0 || a >= M || b >= N) continue;
flip(v, a, b);
}
if (seen.count(v)) continue;
seen.insert(v);
q.push(v);
}
}
}
++step;
}
return -1;
}
};

• class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if mat[i][j])
q = deque([state])
vis = {state}
ans = 0
dirs = [0, -1, 0, 1, 0, 0]
while q:
for _ in range(len(q)):
state = q.popleft()
if state == 0:
return ans
for i in range(m):
for j in range(n):
nxt = state
for k in range(5):
x, y = i + dirs[k], j + dirs[k + 1]
if not 0 <= x < m or not 0 <= y < n:
continue
if nxt & (1 << (x * n + y)):
nxt -= 1 << (x * n + y)
else:
nxt |= 1 << (x * n + y)
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
return -1

• func minFlips(mat [][]int) int {
m, n := len(mat), len(mat[0])
state := 0
for i, row := range mat {
for j, v := range row {
if v == 1 {
state |= 1 << (i*n + j)
}
}
}
q := []int{state}
vis := map[int]bool{state: true}
ans := 0
dirs := []int{0, -1, 0, 1, 0, 0}
for len(q) > 0 {
for t := len(q); t > 0; t-- {
state = q[0]
if state == 0 {
return ans
}
q = q[1:]
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
nxt := state
for k := 0; k < 5; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x < 0 || x >= m || y < 0 || y >= n {
continue
}
if (nxt & (1 << (x*n + y))) != 0 {
nxt -= 1 << (x*n + y)
} else {
nxt |= 1 << (x*n + y)
}
}
if !vis[nxt] {
vis[nxt] = true
q = append(q, nxt)
}
}
}
}
ans++
}
return -1
}