题意:给定一个01矩阵,每次可以翻转一个数字,同时它的上下左右也会翻转,求最少翻转次数使得矩阵全为1
题解:n <=3, m <= 3,状压dp表示第i,j个坐标是否翻转,求最小次数即可。
AC代码:
class Solution {
public:
int minFlips(vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
int sz = n * m;
int ans = 1e9;
for (int i = 0; i < 1 << sz; i++) {
auto dummy = mat;
int sum = 0;
for (int j = 0; j < sz; j++) {
if (i & (1 << j)) {
sum++;
int x = j / m;
int y = j % m;
dummy[x][y] ^= 1;
if (x != 0) dummy[x - 1][y] ^= 1;
if (y != 0) dummy[x][y - 1] ^= 1;
if (x != n - 1) dummy[x + 1][y] ^= 1;
if (y != m - 1) dummy[x][y + 1] ^= 1;
}
}
bool check = true;
for (auto it : dummy) {
for (auto j : it) {
if (j == 1) check = false;
}
}
if (check) ans = min(ans, sum);
}
return ans == 1e9 ? -1 : ans;
}
};