#3240
Medium Algorithms Minimum number of flips to make binary grid palindromic ii
Array Two Pointers Matrix
25.4% acceptance
Feb 25, 2026
142
57
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn min_flips(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut cost = 0i32;
// Interior groups of 4: (r, c), (r, n-1-c), (m-1-r, c), (m-1-r, n-1-c)
for r in 0..m / 2 {
for c in 0..n / 2 {
let cnt = grid[r][c] + grid[r][n - 1 - c] + grid[m - 1 - r][c] + grid[m - 1 - r][n - 1 - c];
cost += cnt.min(4 - cnt);
}
}
// Middle row/col pairs to force even # of paired-1s
let mut forced_1 = 0i32; // # middle pairs where both cells = 1
let mut free = 0i32; // # middle pairs with one 0 and one 1 (cost 1, flexible value)
// Middle row (if m odd): pairs (m/2, c) and (m/2, n-1-c) for c in 0..n/2
if m % 2 == 1 {
for c in 0..n / 2 {
let a = grid[m / 2][c];
let b = grid[m / 2][n - 1 - c];
if a == 1 && b == 1 {
forced_1 += 1;
} else if a != b {
cost += 1;
free += 1;
}
}
}
// Middle col (if n odd): pairs (r, n/2) and (m-1-r, n/2) for r in 0..m/2
if n % 2 == 1 {
for r in 0..m / 2 {
let a = grid[r][n / 2];
let b = grid[m - 1 - r][n / 2];
if a == 1 && b == 1 {
forced_1 += 1;
} else if a != b {
cost += 1;
free += 1;
}
}
}
// Divisibility by 4: # ones from pairs must be even (each pair contributes 0 or 2)
// forced_1 + free_1 must be even; we set free_1=0 initially
if forced_1 % 2 == 1 {
if free > 0 {
// No extra cost: change one free pair from 0 to 1 (already paid for it)
} else {
// Must flip a forced pair at cost 2
cost += 2;
}
}
// Center cell (if both m and n odd): must be 0
if m % 2 == 1 && n % 2 == 1 {
cost += grid[m / 2][n / 2];
}
cost
}
}