【leetcode】1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
题目如下:
Given a
m x nbinary matrixmat. 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
matto 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: 6Example 4:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can't be a zero matrixConstraints:
m == mat.lengthn == mat[0].length1 <= m <= 31 <= n <= 3mat[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
【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. 这题的重点是数据范围,比赛结束看了眼数 ...
- 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)
[LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...
- 【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) suba ...
- 【LeetCode】871. Minimum Number of Refueling Stops 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 贪心算法 日期 题目地址:https://leetc ...
- 【leetcode】452. Minimum Number of Arrows to Burst Balloons
题目如下: 解题思路:本题可以采用贪心算法.首先把balloons数组按end从小到大排序,然后让第一个arrow的值等于第一个元素的end,依次遍历数组,如果arrow不在当前元素的start到en ...
- 【LeetCode】762. Prime Number of Set Bits in Binary Representation 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历数字+质数判断 日期 题目地址:https:// ...
- 【leetcode】963. Minimum Area Rectangle II
题目如下: Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from ...
- 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)
[LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...
- 【LeetCode】137. Single Number II 解题报告(Python)
[LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...
随机推荐
- selenium 鼠标,键盘操作
1.打开和关闭网页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #!/usr/bin/env python # -*- coding:u ...
- 从入门到自闭之Python集合,深浅拷贝(大坑)
小数据池 int: -5~256 str: 字母,数字长度任意符合驻留机制 字符串进行乘法时总长度不能超过20 特殊符号进行乘法时只能乘以0 代码块: 一个py文件,一个函数,一个模块,终端中的每一行 ...
- Maven学习存档(1)——安装
一.安装 1.1 jdk的下载与安装 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 版本:maven2 ...
- 关闭钩子(shutdown hook)的作用以及在Tomcat中的使用
在很多实际应用环境中,当用户关了应用程序时,需要做一些善后清理工作,但问题是,用户有时并不会按照推荐的方法关闭应用程序,很有可能不做清理工作,例如在Tomcat的部署应用中,通过实例化一个Server ...
- Java Web ClassLoader工作机制
一.ClassLoader的作用: 1.类加载机制:父优先的等级加载机制 2.类加载过程 3.将Class字节码重新解析成JVM统一要求的对象格式 二.ClassLoader常用方法 1.define ...
- pymssql文档(转)
pymssql methods set_max_connections(number) -- Sets maximum number of simultaneous database connecti ...
- jQuery快速入门专题
jQuery入门专题 本人博客特点:最高重要等级为*****(五红星),依次减少代表重要性相对较低! 一.jQuery简介 jQuery 是一个 JavaScript的一个库,也就是说jQuery是基 ...
- C# 移除数组中重复项
方法一: static void Main(string[] args) { //看到数组的第一反应应该是排序 ,,,,,,,}; //去掉数组中重复的项 //先排序 arrayAsc(array); ...
- img 图像底部留白的原因以及解决方法
有时候,我们在添加图片img标签后并没有给该标签设置magrin属性的margin-bottom值,在有些浏览器中打开就会出现图像底部留白,为什么为造成这个原因?下面就来进行分析:由于img元素默认为 ...
- shell运行下的写日志
tee 重定向输出到多个文件 在执行Linux命令时,我们既想把输出保存到文件中,又想在屏幕上看到输出内容,就可以使用tee命令 要注意的是:在使用管道线时,前一个命令的标准错误输出不会被tee读 ...
