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

3239. Minimum Number of Flips to Make Binary Grid Palindromic I

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 either all rows palindromic or all columns palindromic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int minFlips(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size(), r = 0, c = 0;
for(int i = 0; i < n / 2; i++) {
for(int j = 0; j < m / 2; j++) {
if(grid[i][j] != grid[i][m-j-1]) r++;
if(grid[i][j] != grid[n-i-1][j]) c++;
}
}
for(int i = n / 2; i < n; i++) {
for(int j = m / 2; j < m; j++) {
if(grid[i][j] != grid[i][m-j-1]) r++;
if(grid[i][j] != grid[n-i-1][j]) c++;
}
}
return min(r,c);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/04/PS/LeetCode/minimum-number-of-flips-to-make-binary-grid-palindromic-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.