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.

思路:BFS,数组tuple话存到set

class Solution(object):
    def minFlips(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: int
        """
        import copy
        m,n=len(mat),len(mat[0])
        q,qq=[tuple([tuple(s) for s in mat])],[]
        vis=set(q)
        dirs=[[0,0],[1,0],[-1,0],[0,1],[0,-1]]
        step=0
        while q:
            while q:
                s=q.pop()
                if sum(sum(c) for c in s)==0: return step
                s=[list(c) for c in s]
                for i in range(m):
                    for j in range(n):
                        ss=copy.deepcopy(s)
                        for di,dj in dirs:
                            ii,jj=i+di,j+dj
                            if 0<=ii<m and 0<=jj<n:
                                ss[ii][jj]=1-ss[ii][jj]
                        cand = tuple([tuple(c) for c in ss])
                        if cand in vis: continue
                        vis.add(cand)
                        qq.append(cand)
            q,qq=qq,q
            step+=1
        return -1

s=Solution()
print(s.minFlips([[0,0],[0,1]]))
print(s.minFlips([[0]]))
print(s.minFlips([[1,1,1],[1,0,1],[0,0,0]]))
print(s.minFlips([[1,0,0],[1,0,0]]))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值