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.
题解:
数据量非常小(9 * 9),暴力枚举所有情况即可。
class Solution {
public:
void flip(int x, int y, int m, int n, vector<vector<int>>& mat) {
mat[x][y] = mat[x][y] ^ 1;
if (x - 1 >= 0) {
mat[x - 1][y] = mat[x - 1][y] ^ 1;
}
if (x + 1 < m) {
mat[x + 1][y] = mat[x + 1][y] ^ 1;
}
if (y - 1 >= 0) {
mat[x][y - 1] = mat[x][y - 1] ^ 1;
}
if (y + 1 < n) {
mat[x][y + 1] = mat[x][y + 1] ^ 1;
}
}
bool judge(vector<vector<int>>& mat, int &m, int &n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
return false;
}
}
}
return true;
}
void dfs(int x, int y, int m, int n, vector<vector<int>> &mat, int cnt, int &res) {
if (y == n) {
y = 0;
x++;
}
if (x == m) {
if (judge(mat, m, n) == true) {
res = min(res, cnt);
}
return;
}
flip(x, y, m, n, mat);
dfs(x, y + 1, m, n, mat, cnt + 1, res);
flip(x, y, m, n, mat);
dfs(x, y + 1, m, n, mat, cnt, res);
}
int minFlips(vector<vector<int>>& mat) {
if (mat.empty() == true) {
return -1;
}
int m = mat.size(), n = mat[0].size();
int res = INT_MAX;
dfs(0, 0, m, n, mat, 0, res);
if (res == INT_MAX) {
return -1;
}
return res;
}
};