3239. Minimum Number of Flips to Make Binary Grid Palindromic I
Description
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.
Example 1:
Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
Output: 2
Explanation:
Flipping the highlighted cells makes all the rows palindromic.
Example 2:
Input: grid = [[0,1],[0,1],[0,0]]
Output: 1
Explanation:
Flipping the highlighted cell makes all the columns palindromic.
Example 3:
Input: grid = [[1],[0]]
Output: 0
Explanation:
All rows are already palindromic.
Constraints:
m == grid.lengthn == grid[i].length1 <= m * n <= 2 * 1050 <= grid[i][j] <= 1
Solutions
Solution 1: Counting
Thinking
We may make every row a palindrome or every column a palindrome, and want the fewer flips. \(mn\le 2\times 10^5\), so count both costs and take the min.
A row needs one flip per mismatched pair; columns are analogous. The two counts are independent. The matrix need not be rewritten.
We separately count the number of flips for rows and columns, denoted as \(\textit{cnt1}\) and \(\textit{cnt2}\), respectively. Finally, we take the minimum of the two.
The time complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns of the matrix \(\textit{grid}\), respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |

