class Solution {
public:
int minFlips(vector<vector<int>>& mat) {
const int M = mat.size(), N = mat[0].size();
int bitmap = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
bitmap |= mat[i][j] << (i * N + j);
}
}
vector<vector<int>> dirs{{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {0, 0}};
const auto flip = [&](int bitmap, int i, int j) {
for (const auto &d : dirs) {
int r = i + d[0], c = j + d[1];
if (r >= 0 && r < M && c >= 0 && c < N) {
bitmap ^= 1 << (r * N + c);
}
}
return bitmap;
};
queue<int> q;
unordered_set<int> visited(bitmap);
q.push(bitmap);
for (int cnt = 0; !q.empty(); ++cnt) {
for (int size = q.size(); size > 0; --size) {
bitmap = q.front(); q.pop();
if (bitmap == 0) return cnt;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
const auto next = flip(bitmap, i, j);
if (visited.count(next)) continue;
visited.insert(next);
q.push(next);
}
}
}
}
return -1;
}
};