【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 minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.

Binary matrix is a matrix with all cells equal to 0 or 1 only.

Zero matrix is a matrix with all cells equal to 0.

Example 1:

Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

Example 2:

Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We don‘t need to change it.

Example 3:

Input: mat = [[1,1,1],[1,0,1],[0,0,0]]
Output: 6

Example 4:

Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can‘t be a zero matrix

Constraints:

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

解题思路:最大就是3*3的矩阵,BFS把每种情况都试一遍就好了。

代码如下:

class Solution(object):
    def minFlips(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: int
        """
        import copy
        def isAllZero(grid):
            count = 0
            for i in grid:
                count += sum(i)
            return count == 0

        def encode(grid):
            grid_s = ‘‘
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    grid_s += str(grid[i][j])
                if i != len(grid) - 1 : grid_s += ‘#‘
            return grid_s
        def decode(grid_s):
            gl = grid_s.split(‘#‘)
            grid = []
            for i in gl:
                tl = []
                for j in list(i):
                    tl.append(int(j))
                grid.append(tl)
            return grid

        res = float(‘inf‘)
        queue = [(encode(mat),0)]
        dic = {}
        dic[encode(mat)] = 0

        while len(queue) > 0:
            gs,step = queue.pop(0)
            grid = decode(gs)
            if isAllZero(grid):
                res = min(res,step)
                continue
            elif res <= step:
                continue
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    #if grid[i][j] == 0: continue
                    new_grid = copy.deepcopy(grid)
                    if new_grid[i][j] == 1:
                        new_grid[i][j] = 0
                    else:new_grid[i][j] = 1
                    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
                    for (x, y) in directions:
                        if x + i >= 0 and x + i < len(grid) and y + j >= 0 and y + j < len(grid[0]):
                            if new_grid[x + i][y + j] == 0:
                                new_grid[x + i][y + j] = 1
                            else:
                                new_grid[x + i][y + j] = 0
                    encode_Str = encode(new_grid)
                    if encode_Str not in dic or dic[encode_Str] > step + 1:
                        queue.append((encode(new_grid), step + 1))
                        dic[encode_Str] = step + 1
        return res if res != float(‘inf‘) else -1

原文地址:https://www.cnblogs.com/seyjs/p/12026296.html

时间: 2024-08-30 05:13:25

【leetcode】1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix的相关文章

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个格子.....暴力怎么都能搞出来的..... 首先分析每个格子要么不反转,

【leetcode】995. Minimum Number of K Consecutive Bit Flips

题目如下: 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

【leetcode】1347. Minimum Number of Steps to Make Two Strings Anagram

题目如下: Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same c

【LeetCode】Find Minimum in Rotated Sorted Array 解题报告

今天看到LeetCode OJ题目下方多了"Show Tags"功能.我觉着挺好,方便刚開始学习的人分类练习.同一时候也是解题时的思路提示. [题目] Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no

【LeetCode】462. Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10

【leetcode】1210. Minimum Moves to Reach Target with Rotations

题目如下: In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0)and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right co

【leetcode】1249. Minimum Remove to Make Valid Parentheses

题目如下: Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a

【leetcode】Find Minimum in Rotated Sorted Array JAVA实现

一.题目描述 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array. 二.分析 这题难度有,因为他默认的是数组中所有的元素是不同的.只有分为两种情况: 1.

【LeetCode】Find Minimum in Rotated Sorted Array 在旋转数组中找最小数

Add Date 2014-10-15 Find Minimum in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the