【leetcode】1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
题目如下:
Given a
m x n
binary 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
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: 6Example 4:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can't be a zero matrixConstraints:
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
【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- ...
随机推荐
- Codeforces Round #333 (Div. 2) B. Approximating a Constant Range
B. Approximating a Constant Range Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com ...
- 小米soar
SOAR 简介 SOAR,即 SQL Optimizer And Rewriter,是一款 SQL 智能优化与改写工具,由小米运维 DBA 团队出品 SOAR 体系架构 SOAR主要由语法解析器,集成 ...
- Java回调实现异步 (转)
出处: Java回调实现异步 在正常的业务中使用同步线程,如果服务器每处理一个请求,就创建一个线程的话,会对服务器的资源造成浪费.因为这些线程可能会浪费时间在等待网络传输,等待数据库连接等其他事情上, ...
- Docker-PS命令解析
查看 docker 容器,必然要用到 docker ps 命令.其基本格式为: docker ps [OPTIONS] 关键在于 OPTIONS(选项): 1 常见用法 1. 最常见的用法 $ doc ...
- 关于win10安卓真机调试无法找到设备的问题
之前在win10系统上调试安卓设备,usb接好了,结果居然没有找到设备. 一般出现这种情况可能是电脑的驱动没装好. 于是找了驱动人生大佬来诊断,确实是少了安卓usb驱动. 正常来说用驱动人生装个usb ...
- Online Meeting CodeForces - 420B (思维)
大意: 给定某一段连续的上线下线记录, 老板上线或下线时房间无人, 并且每次会议都在场, 求哪些人可能是老板. 结论1: 从未出现过的人一定可以是老板. 结论2: 出现过的人中老板最多只有1个. 结论 ...
- Java EE javax.servlet中的ServletConfig接口
ServletConfig接口 public interface ServletConfig 实现类:GenericServlet.HttpServlet 一.介绍 一个供servlet容器使用配置对 ...
- Kafka网络模型
摘要:很多人喜欢把RocketMQ与Kafka做对比,其实这两款消息队列的网络通信层还是比较相似的,本文就为大家简要地介绍下Kafka的NIO网络通信模型,通过对Kafka源码的分析来简述其React ...
- prefixOverrides使用注意是事项
不可以prefixOverrides=',' 否则执行的sql格式可能为 id ,time ,name... 导致sql报错,或者执行结果出错
- JS基础_if注意问题
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...