[LeetCode] Minimum Number of Flips to Make Binary Grid Palindromic II

3240. Minimum Number of Flips to Make Binary Grid Palindromic II

You are given an m x n binary matrix grid.

A row or column is considered palindromic if its values read the same forward and backward.

You can flip any number of cells in grid from 0 to 1, or from 1 to 0.

Return the minimum number of cells that need to be flipped to make all rows and columns palindromic, and the total number of 1‘s in grid divisible by 4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
int cost(vector<int> freq) {
int ma = 0, buc[2]{};
for(auto& f : freq) ma = max(ma, ++buc[f]);
return freq.size() - ma;
}
public:
int minFlips(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size(), res = 0;
for(int i = 0; i < n / 2; i++) {
for(int j = 0; j < m / 2; j++) {
res += cost({grid[i][j], grid[i][m-j-1], grid[n-i-1][j], grid[n-i-1][m-j-1]});
}
}
vector<vector<int>> cnt(2,vector<int>(2));
if(n & 1) {
for(int l = 0, r = m - 1; l < r; l++,r--) {
int a = grid[n/2][l], b = grid[n/2][r];
if(a > b) swap(a,b);
cnt[a][b]++;
}
}
if(m & 1) {
for(int l = 0, r = n - 1; l < r; l++,r--) {
int a = grid[l][m/2], b = grid[r][m/2];
if(a > b) swap(a,b);
cnt[a][b]++;
}
}
if(cnt[1][1] % 2 == 0) {
res += cnt[0][1];
} else {
res += cnt[0][1];
if(cnt[0][1] == 0) res += 2;
}
if(n & 1 and m & 1 and grid[n/2][m/2]) res++;
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/04/PS/LeetCode/minimum-number-of-flips-to-make-binary-grid-palindromic-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.