Minimum Number of Flips to Make Binary Grid Palindromic II Problem
Description
LeetCode Problem 3240.
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.
Example 1:
Input: grid = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Explanation:

Example 2:
Input: grid = [[0,1],[0,1],[0,0]]
Output: 2
Explanation:

Example 3:
Input: grid = [[1],[1]]
Output: 2
Explanation:

Constraints:
m == grid.lengthn == grid[i].length1 <= m * n <= 2 * 10^50 <= grid[i][j] <= 1
Solution
Approach: Case Analysis
Now every row and every column must be a palindrome, and the number of 1s must be divisible by 4. For each i < m / 2 and j < n / 2, the four cells (i, j), (m-1-i, j), (i, n-1-j), (m-1-i, n-1-j) must all be equal. If c of them are 1, making them equal costs min(c, 4 - c); add this to the answer.
Then handle the middle:
- If
mandnare both odd, the centre cell must be0(otherwise the count of1s is not divisible by4), so add its value. - If
mis odd, look at the middle row; ifnis odd, look at the middle column. In each of them the cells pair up; letdiffbe the number of pairs whose cells differ andcnt1the number of1s in equal pairs (each such pair contributes two). - If
cnt1is divisible by4, ordiff > 0, the cost isdiff(a differing pair can be fixed to adjust the count of1s by2at no extra cost). Otherwisecnt1 % 4 == 2anddiff == 0, so turn one pair into0s at cost2.
Complexity: O(mn) time, O(1) space, where m and n are the numbers of rows and columns.
class Solution:
def minFlips(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for i in range(m // 2):
for j in range(n // 2):
x, y = m - i - 1, n - j - 1
cnt1 = grid[i][j] + grid[x][j] + grid[i][y] + grid[x][y]
ans += min(cnt1, 4 - cnt1)
if m % 2 and n % 2:
ans += grid[m // 2][n // 2]
diff = cnt1 = 0
if m % 2:
for j in range(n // 2):
if grid[m // 2][j] == grid[m // 2][n - j - 1]:
cnt1 += grid[m // 2][j] * 2
else:
diff += 1
if n % 2:
for i in range(m // 2):
if grid[i][n // 2] == grid[m - i - 1][n // 2]:
cnt1 += grid[i][n // 2] * 2
else:
diff += 1
ans += diff if cnt1 % 4 == 0 or diff else 2
return ans