Given a m x n binary matrix mat.
In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1).
A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
[[0, 0], [0, 1]] 의 경우
from typing import List, Tuple
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
# 양 옆, 위, 아래를 뒤집는 함수
def flip(mat, row, col) -> None:
for r, c in [(row, col), (row-1, col), (row+1, col), (row, col-1), (row, col+1)]:
if 0 <= r < len(mat) and 0 <= c < len(mat[0]):
mat[r][c] ^= 1
# 모든 경우의 수를 탐색하기 위한 BFS
def bfs(mat) -> int:
## BFS를 위한 큐
queue: List[Tuple[List[List[int]], int]] = [(mat, 0)]
## 중복 상태를 방지하기 위한 set
visited = {str(mat)}
while queue:
curr, steps = queue.pop(0)
# 모두 0이면 바로 리턴
if all(all(cell == 0 for cell in row) for row in curr):
return steps
# 모든 뒤집을 수 있는 수에 대해 탐색한다.
for r in range(len(mat)):
for c in range(len(mat[0])):
temp = [row[:] for row in curr]
flip(temp, r, c)
# 한번도 나오지 않은 상태일 경우에만 참고한다.
if str(temp) not in visited:
visited.add(str(temp))
queue.append((temp, steps+1))
return -1