LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix (最少翻转次数将二进制矩阵全部置为0)

给一个矩阵mat,每个格子都是0或1,翻转一个格子会将该格子以及相邻的格子(有共同边)全部翻转(0变为1,1变为0)

求问最少需要翻转几次将所有格子全部置为0。

这题的重点是数据范围,比赛结束看了眼数据范围想把自己锤死= =

  • m == mat.length
  • n == mat[0].length
  • 1 <= m <= 3
  • 1 <= n <= 3
  • mat[i][j] is 0 or 1.

也就是。。。。最多也就9个格子。。。。。暴力怎么都能搞出来的。。。。。

首先分析每个格子要么不反转,要么翻转一次,因为翻转2次的效果和不反转是一样的,不需要在考虑两次及以上的情况。

所以问题很简单,DFS 瞎搞搞就好了~~~

/**
 * @param {number[][]} mat
 * @return {number}
 */
/**
 * 获取一个二维数组的行数和列数
 * @param {any[][]} matrix
 */
const getMatrixRowAndCol = (matrix) => matrix.length === 0 ? [0, 0] : [matrix.length, matrix[0].length];
/**
 * 翻转矩阵第index个元素
 * @param {any [][]} matrix
 * @param {number} index
 * @param {any} value
 */
function flipMatrix(matrix, x, y, r, c) {
    let dir = [[0,1],[0,-1],[1,0],[-1,0]];
    matrix[x][y] = 1 - matrix[x][y];
    for (let i = 0; i < 4; i++) {
        let nx = x + dir[i][0];
        let ny = y + dir[i][1];
        if (nx < r && nx >= 0 && ny < c && ny >= 0) {
            matrix[nx][ny] = 1 - matrix[nx][ny];
        }
    }
}

var minFlips = function(mat) {
    let [r, c] = getMatrixRowAndCol(mat);

    const dfs = (i, j, cnt) => {
        // console.log(i,j,cnt);
        if (i === r) {
            if (mat.every(col => col.every(item => !item))) return cnt;
            return -1;
        }
        if (j === c) {
            return dfs(i+1, 0, cnt);
        }
        let result = -1;
        // not flip (i, j)
        if ((result = dfs(i, j+1, cnt)) != -1) {
            return result;
        }
        // flip (i, j)
        flipMatrix(mat, i, j, r, c);
        if ((result = dfs(i, j+1, cnt+1)) != -1) {
            return result;
        }
        flipMatrix(mat, i, j, r, c);
        return -1;
    }

    return dfs(0, 0, 0);
};

当然,既然题目是二进制矩阵,所以可以有更优雅点的做法,就是用一个二进制数来表示一种情况,二进制数的每一个表示对应格子是否翻转。那么,如果有n个格子,0~(2^n-1) 就可以表示所有情况了。

/**
 * @param {number[][]} mat
 * @return {number}
 */
/**
 * 获取一个二维数组的行数和列数
 * @param {any[][]} matrix
 */
const getMatrixRowAndCol = (matrix) => matrix.length === 0 ? [0, 0] : [matrix.length, matrix[0].length];
/**
 * 翻转矩阵第index个元素
 * @param {any [][]} matrix
 * @param {number} index
 * @param {any} value
 */
function flipMatrix(matrix, x, y, r, c) {
    let dir = [[0,1],[0,-1],[1,0],[-1,0]];
    matrix[x][y] = 1 - matrix[x][y];
    for (let i = 0; i < 4; i++) {
        let nx = x + dir[i][0];
        let ny = y + dir[i][1];
        if (nx < r && nx >= 0 && ny < c && ny >= 0) {
            matrix[nx][ny] = 1 - matrix[nx][ny];
        }
    }
}

var minFlips = function(mat) {
    let [r, c] = getMatrixRowAndCol(mat);
    let n = r * c;

    // 一共有 n 个格子 每个格子有两种选择 不翻转(0) 翻转(1)
    // 所以可以用 n 位二进制数来表示格子的翻转情况
    let stateNum = (1 << n) - 1;
    for (let state = 0; state <= stateNum; state++) {
        // 获取 mat 的一个副本用来修改
        let copyMat = mat.map(item => ([...item]));
        let flipCnt = 0;
        // state 代表一种翻转情况 每一个二进制都表示对应格子是否翻转
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                let index = i * c + j;
                if ((1 << index) & state) {
                    flipCnt++;
                    flipMatrix(copyMat, i, j, r, c);
                }
            }
        }
        if (copyMat.every(col => col.every(item => !item))) return flipCnt;
    }

    return -1;
};

原文地址:https://www.cnblogs.com/wenruo/p/12005805.html

时间: 2024-08-30 15:06:30

LeetCode 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix (最少翻转次数将二进制矩阵全部置为0)的相关文章

【leetcode】1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

题目如下: Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge. Return the min

LeetCode | 0452. Minimum Number of Arrows to Burst Balloons用最少数量的箭引爆气球【Python】

LeetCode 0452. Minimum Number of Arrows to Burst Balloons用最少数量的箭引爆气球[Medium][Python][区间贪心] Problem LeetCode There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of

[LeetCode] 452 Minimum Number of Arrows to Burst Balloons

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of s

452. Minimum Number of Arrows to Burst Balloons扎气球的个数最少

[抄题]: There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinate

[LeetCode] 871. Minimum Number of Refueling Stops 最少的加油站个数

A car travels from a starting position to a destination which is?target?miles east of the starting position. Along the way, there are gas stations.? Each?station[i]?represents a gas station that is?station[i][0]?miles east of the starting position, a

LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram

题目 用hash,比较两个字符串数组的每个字符的hash值 class Solution { public: int m[300]; int m2[300]; int minSteps(string s, string t) { for(int i=0;i<s.length();i++) { m[s[i]]++; } for(int i=0;i<t.length();i++) { m2[t[i]]++; } int ans=0; int steps=0; for(int i=0;i<30

Leetcode 762. Prime Number of Set Bits in Binary Representation

思路:动态规划.注意1024*1024>10^6,所以质素范围是(0,23). 1 class Solution { 2 public int countPrimeSetBits(int L, int R) { 3 Set<Integer> prime = new HashSet<Integer>(Arrays.asList(2,3,5,7,11,13,17,19,23)); 4 int[] count = new int[1+R]; 5 int res = 0; 6 for

Minimum number of swaps required to sort an array

https://www.hackerrank.com/challenges/minimum-swaps-2/problem Minimum Swaps II You are given an unordered array consisting of consecutive integers  [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find t

[LeetCode] Minimum Number of K Consecutive Bit Flips 连续K位翻转的最小次数

In an array?A?containing only 0s and 1s, a?K-bit flip?consists of choosing a (contiguous) subarray of length?K?and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of?K-bit flips requir