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

CNoodle發表於2024-11-15

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);
    }
}

相關文章