题目描述:
方法一:暴力BFS
class Solution: def minFlips(self, mat) -> int: R, C = len(mat), len(mat[0]) def helper(mat): return tuple(tuple(row) for row in mat) visited = set() queue = collections.deque() mat_ = helper(mat) visited.add(mat_) queue.append(mat) ans = 0 while queue: for _ in range(len(queue)): cur = queue.popleft() if sum(sum(row) for row in cur) == 0: return ans for i in range(R): for j in range(C): cur1 = [row[:] for row in cur] #列表的复制一定要深copy for i_, j_ in [[i, j], [i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]]: if 0 <= i_ < R and 0 <= j_ < C: cur1[i_][j_] ^= 1 cur_ = helper(cur1) if cur_ not in visited: visited.add(cur_) queue.append(cur1) ans += 1 return -1
方法二:暴力枚举
class Solution: def minFlips(self, mat) -> int: R,C = len(mat),len(mat[0]) N = R*C ans = R*C + 1 for i in itertools.product(range(2),repeat = N): bns = sum(i) if bns >= ans: continue r = c = 0 B = [row[:] for row in mat] for adj in i: if adj: for i_,j_ in [[r,c],[r+1,c],[r-1,c],[r,c+1],[r,c-1]]: if 0 <= i_ < R and 0 <= j_ < C: B[i_][j_] ^= 1 c += 1 if c == C: c = 0 r += 1 if sum(sum(row)for row in B) == 0: ans = bns return ans if ans < N+1 else -1