[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实现

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);
    }
}
posted @ 2024-11-15 02:42  CNoodle  阅读(3)  评论(0编辑  收藏  举报