You are given an m x n binary matrix grid where each cell contains either 0 or 1. Your goal is to make the entire grid follow a palindromic pattern by flipping the minimum number of cells.
A palindromic pattern means that either:
- All rows are palindromic (each row reads the same forwards and backwards), OR
- All columns are palindromic (each column reads the same top-to-bottom and bottom-to-top)
You can flip any cell from 0 to 1 or from 1 to 0. Return the minimum number of flips needed to achieve one of these two palindromic arrangements.
Example: For matrix [[1,0,0],[0,1,0],[1,1,1]], you need to choose between making all rows palindromic or all columns palindromic, whichever requires fewer flips.
Input & Output
Visualization
Time & Space Complexity
We visit each cell exactly twice - once during row analysis and once during column analysis
Only using constant extra space for pointer variables and counters
Constraints
- 1 โค m, n โค 300
- grid[i][j] is either 0 or 1
- Time limit: 2 seconds
- Space limit: 256 MB