1284.cpp (1163B)
1 class Solution { 2 public: 3 int minFlips(const vector<vector<int>> &mat) const { 4 static const int offset[] = {-1, 0, 1, 0, -1}; 5 const int n = size(mat), m = size(mat[0]); 6 unsigned res = -1; 7 8 const auto valid = [&](int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }; 9 10 for (unsigned mask = 0; mask < 1 << (n * m); mask++) { 11 auto grid = mat; 12 13 for (unsigned k = 0, crnt = mask; crnt; crnt >>= 1, k++) { 14 if (!(crnt & 1)) continue; 15 16 const int a = k / m, b = k % m; 17 for (int k = 0; k < 4; k++) { 18 const int x = a + offset[k + 1]; 19 const int y = b + offset[k]; 20 21 if (!valid(x, y)) continue; 22 grid[x][y] = !grid[x][y]; 23 } 24 grid[a][b] = !grid[a][b]; 25 } 26 27 for (int i = 0; i < n; i++) { 28 for (int j = 0; j < m; j++) { 29 if (grid[i][j]) goto next; 30 } 31 } 32 33 res = min(res, (unsigned)popcount(mask)); 34 next:; 35 } 36 37 return res; 38 } 39 };