Minimum Number of Flips to Make Binary Grid Palindromic II - Problem
Transform a Binary Grid into Perfect Palindromic Harmony
You are given an
๐ Palindromic Perfection: Every row and every column must read the same forwards and backwards (palindromic)
๐ข Divisibility Rule: The total count of
You can flip any cell from
Goal: Return the minimum number of flips needed to achieve both conditions.
Example:
You are given an
m ร n binary matrix grid containing only 0s and 1s. Your mission is to transform this grid to satisfy two challenging conditions simultaneously:๐ Palindromic Perfection: Every row and every column must read the same forwards and backwards (palindromic)
๐ข Divisibility Rule: The total count of
1s in the entire grid must be divisible by 4You can flip any cell from
0 to 1 or from 1 to 0. Each flip counts as one operation.Goal: Return the minimum number of flips needed to achieve both conditions.
Example:
[[1,0,0],[0,1,0],[0,0,1]] โ Minimum flips needed to make all rows/columns palindromic AND total 1s divisible by 4. Input & Output
example_1.py โ Small Grid
$
Input:
grid = [[1,0,0],[0,1,0],[0,0,1]]
โบ
Output:
3
๐ก Note:
Need to make rows and columns palindromic AND total 1s divisible by 4. Current grid has 3 ones. To make palindromic: (0,0)=1 must equal (0,2)=0 and (2,0)=0 must equal (2,2)=1, etc. Optimal solution flips 3 cells to achieve both conditions.
example_2.py โ Symmetric Grid
$
Input:
grid = [[0,1,0],[1,0,1],[0,1,0]]
โบ
Output:
0
๐ก Note:
This grid is already palindromic in all rows and columns: [0,1,0] reads same forwards/backwards, and column [0,1,0] also palindromic. Total 1s = 4, which is divisible by 4. No flips needed.
example_3.py โ Edge Case
$
Input:
grid = [[1,1],[1,1]]
โบ
Output:
0
๐ก Note:
All rows [1,1] and columns [1,1] are already palindromic. Total 1s = 4, divisible by 4. Perfect as-is, 0 flips needed.
Constraints
- 1 โค m, n โค 1000
- grid[i][j] is either 0 or 1
- m ร n โค 106 (total cells limited)
- Solution must satisfy both palindromic AND divisibility conditions
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code