题目如下:

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

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

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

    给一个矩阵mat,每个格子都是0或1,翻转一个格子会将该格子以及相邻的格子(有共同边)全部翻转(0变为1,1变为0) 求问最少需要翻转几次将所有格子全部置为0. 这题的重点是数据范围,比赛结束看了眼数 ...

  2. 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)

    [LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...

  3. 【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 ...

  4. 【LeetCode】871. Minimum Number of Refueling Stops 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 贪心算法 日期 题目地址:https://leetc ...

  5. 【leetcode】452. Minimum Number of Arrows to Burst Balloons

    题目如下: 解题思路:本题可以采用贪心算法.首先把balloons数组按end从小到大排序,然后让第一个arrow的值等于第一个元素的end,依次遍历数组,如果arrow不在当前元素的start到en ...

  6. 【LeetCode】762. Prime Number of Set Bits in Binary Representation 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历数字+质数判断 日期 题目地址:https:// ...

  7. 【leetcode】963. Minimum Area Rectangle II

    题目如下: Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from ...

  8. 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)

    [LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  9. 【LeetCode】137. Single Number II 解题报告(Python)

    [LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...

随机推荐

  1. Linux_目录基本操作_常用命令【详解】

    Linux_常用命令 Linux文件系统的目录树结构:[Linux世界里一切皆文件]:说白了,就是文件和文件夹(目录)之间的操作. 普通用户kkb所有文件及文件夹,其实都位于root用户的 /home ...

  2. windows环境下使用C++&Socket实现文件传输

    server #include <stdio.h> #include <iostream> #include <cstring> #include <fstr ...

  3. winform中使用TextBox滚动显示日志信息

    代码如下: private void ShowInfo(string msg) { this.BeginInvoke((Action)(() => { textBox1.AppendText(s ...

  4. 树莓派3b 串口乱码的一个解决思路

    首先确认波特率设置正确,为115200 向microSD卡中烧录树莓派官方的镜像后,先不要急着把它插入树莓派中. 在电脑上打开microSD卡,按如下方式修改config.txt和cmdline.tx ...

  5. Qt Model/View理解(二)---构造model(细心研读,发现超简单,Model就是做三件事:返回行数量、列数量、data如何显示。然后把model与view联系起来即可,两个例子都是如此)good

    数据是一个集合,显示也是一个集合.例如一篇<西游记>的文章,所有的文字就是数据集合,展示方式就是显示的集合,可以以书本的形式,也可以以电纸书的形式,更可以用视频的方式展现. 下面是将一个二 ...

  6. tensorflow零起点快速入门(2)

    指定设备与矩阵乘法 使用tf.device("/gpu:0")用于指定设备进行运算. 在使用jupyter notebook的时候,可能会出现使用异常,需要使用config=tf. ...

  7. JS基础_if注意问题

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  8. PS 中混合模式

    1.正常模式 2. 溶解 3. 变暗    :  把两幅图中较暗的区域显示出来 4.正片叠底   总体变暗,把图层中较浅的颜色由下一图层较深的颜色显现(和滤色相反) 7. 深色  取较小的颜色 8. ...

  9. Django-DRF-视图的演变(二)

    Django-DRF-视图的演变   版本一(基于类视图APIView类) views.py: APIView是继承的Django View视图的. 1 from .serializers impor ...

  10. python与pip

    python , pip 相关命令汇总 1) 在python3 下升级pip3 pip3 install --upgrade pip