[LeetCode] 3239. Minimum Number of Flips to Make Binary Grid Palindromic I

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.

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

Explanation:
Flipping the highlighted cells makes all the rows palindromic.

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

Explanation:
Flipping the highlighted cell makes all the columns palindromic.

Example 3:
Input: grid = [[1],[0]]
Output: 0

Explanation:
All rows are already palindromic.

Constraints:
m == grid.length
n == grid[i].length
1 <= m * n <= 2 * 105
0 <= grid[i][j] <= 1

最少翻转次数使二进制矩阵回文 I。

给你一个 m x n 的二进制矩阵 grid 。

如果矩阵中一行或者一列从前往后与从后往前读是一样的,那么我们称这一行或者这一列是 回文 的。

你可以将 grid 中任意格子的值 翻转 ,也就是将格子里的值从 0 变成 1 ,或者从 1 变成 0 。

请你返回 最少 翻转次数,使得矩阵 要么 所有行是 回文的 ,要么所有列是 回文的 。

思路

思路是双指针,看看每一行和每一列是否都是回文。

复杂度

时间O(mn)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int minFlips(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
// every row
int count1 = 0;
for (int i = 0; i < m; i++) {
int left = 0;
int right = n - 1;
while (left < right) {
if (grid[i][left] != grid[i][right]) {
count1++;
}
left++;
right--;
}
}

// every col
int count2 = 0;
for (int i = 0; i < n; i++) {
int up = 0;
int down = m - 1;
while (up < down) {
if (grid[up][i] != grid[down][i]) {
count2++;
}
up++;
down--;
}
}
return Math.min(count1, count2);
}
}

[LeetCode] 3239. Minimum Number of Flips to Make Binary Grid Palindromic I
https://shurui91.github.io/posts/33361896.html
Author
Aaron Liu
Posted on
November 14, 2024
Licensed under