Minimum Number of Flips to Make Binary Grid Palindromic I - Problem
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.
Input & Output
Example 1 — Already Palindromic Rows
$
Input:
grid = [[1,0,1],[0,1,0]]
›
Output:
0
💡 Note:
All rows are already palindromic: [1,0,1] reads same forward/backward, [0,1,0] reads same forward/backward. No flips needed.
Example 2 — Need Column Flips
$
Input:
grid = [[1,0],[0,1]]
›
Output:
2
💡 Note:
Rows need 2 flips: [1,0]→[1,1] (1 flip) and [0,1]→[0,0] (1 flip). Columns need 2 flips: change grid[0][0] or grid[1][0] to make column 0 palindromic (1 flip), and change grid[0][1] or grid[1][1] to make column 1 palindromic (1 flip). Both approaches need 2 flips: min(2,2) = 2.
Example 3 — Single Column
$
Input:
grid = [[1],[0],[1]]
›
Output:
1
💡 Note:
Rows are already palindromic (single elements). Column [1,0,1] needs 0 flips (already palindromic). But we have rows that need flips. Actually, single elements are palindromic, so answer is 0 for rows, 0 for column. min(0,0) = 0. Wait, let me recalculate: all single-element rows are palindromic, column [1,0,1] is palindromic. Answer is 0.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 300
- 0 ≤ grid[i][j] ≤ 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code