1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
# Time: O((m * n) * 2^(m * n))
# Space: O((m * n) * 2^(m * n))
import collections
class Solution(object):
def minFlips(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
directions = [(0, 0), (0, 1), (1, 0), (0, -1), (-1, 0)]
start = sum(val << r*len(mat[0])+c for r, row in enumerate(mat) for c, val in enumerate(row))
q = collections.deque([(start, 0)])
lookup = {start}
while q:
state, step = q.popleft()
if not state:
return step
for r in xrange(len(mat)):
for c in xrange(len(mat[0])):
new_state = state
for dr, dc in directions:
nr, nc = r+dr, c+dc
if 0 <= nr < len(mat) and 0 <= nc < len(mat[0]):
new_state ^= 1 << nr*len(mat[0])+nc
if new_state in lookup:
continue
lookup.add(new_state)
q.append((new_state, step+1))
return -1
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助