题目如下:

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. ASP.NET Core中使用Dapper

    ⒈添加 NuGet 包 Install-Package Dapper ⒉封装数据库类型 using System; using System.Collections.Generic; using Sy ...

  2. markdown中使用缩进

    在markdown中直接敲空格是不生效的. 使用html标签来实现 一个空格大小的表示:  两个空格的大小表示:  不换行空格:  别忘记分号 参考了大神的文章: markdown空格缩进以及HTML ...

  3. Jmeter的基础使用一安装、启动、关联、断言

    一.下载Jmeter,配置环境变量 下载完解压即可, 环境变量配置: -------在环境变量中添加新变量JMETER_HOME:D:\jmeter\apache-jmeter-4.0 ------- ...

  4. 《深入理解 Java 虚拟机》学习 -- 垃圾回收算法

    <深入理解 Java 虚拟机>学习 -- 垃圾回收算法 1. 说明 程序计数器,虚拟机栈,本地方法栈三个区域随线程而生,随线程而灭,这几个区域的内存分配和回收都具备确定性 Java 堆和方 ...

  5. 怎样理解 MVVM ( Model-View-ViewModel ) ?

    MVVM 的 产生 / 实现 / 发展 可以写一篇很长的博客了, 这里仅写一下个人对 MVVM的一些肤浅的认识. 1. 在 没有 MVVM 之前, 前端可以说是 jQuery一把梭 , jQuery ...

  6. 数据结构-二叉搜索树Java实现

    1,Node.java 生成基础二叉树的结构 package com.cnblogs.mufasa.searchTree; /** * 节点配置父+左+右 */ public class Node{ ...

  7. asp.net 13 缓存,Session存储

    1.缓存 将数据从数据库/文件取出来放在服务器的内存中,这样后面的用来获取数据,不用查询数据库,直接从内存(缓冲)中获取数据,提高了访问的速度,节省了时间,也减轻了数据库的压力. 缓冲空间换时间的技术 ...

  8. AutoCAD2013 以上利用AccoreConsole+ c# NetApi Windows Froms 封装

    1# 封装类 public static class CmdHelper { /// <summary> /// 调用AutoCAD 安装目录下的AccoreConsole.exe来实现批 ...

  9. linq多个条件

    public static class PredicateBuilder { /// <summary> /// 机关函数应用True时:单个AND有效,多个AND有效:单个OR无效,多个 ...

  10. JS基础_质数练习的改进,提高程序执行效率

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...