Problem: 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 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`.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def minFlips(self, mat: List[List[int]]) -> int:
    m = len(mat)
    n = len(mat[0])
    hash = self._getHash(mat, m, n)
    if hash == 0:
      return 0

    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    step = 0
    q = collections.deque([hash])
    seen = {hash}

    while q:
      step += 1
      for _ in range(len(q)):
        curr = q.popleft()
        for i in range(m):
          for j in range(n):
            next = curr ^ 1 << (i * n + j)
            for dx, dy in dirs:
              x = i + dx
              y = j + dy
              if x < 0 or x == m or y < 0 or y == n:
                continue
              next ^= 1 << (x * n + y)
            if next == 0:
              return step
            if next in seen:
              continue
            q.append(next)
            seen.add(next)

    return -1

  def _getHash(self, mat: List[List[int]], m: int, n: int) -> int:
    hash = 0
    for i in range(m):
      for j in range(n):
        if mat[i][j]:
          hash |= 1 << (i * n + j)
    return hash


Java solution:
class Solution {
  public int minFlips(int[][] mat) {
    final int m = mat.length;
    final int n = mat[0].length;
    final int hash = getHash(mat, m, n);
    if (hash == 0)
      return 0;

    final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    Queue<Integer> q = new ArrayDeque<>(List.of(hash));
    Set<Integer> seen = new HashSet<>(Arrays.asList(hash));

    for (int step = 1; !q.isEmpty(); ++step) {
      for (int sz = q.size(); sz > 0; --sz) {
        final int curr = q.poll();
        for (int i = 0; i < m; ++i) {
          for (int j = 0; j < n; ++j) {
            int next = curr ^ 1 << (i * n + j);
            // Flie the four neighbors.
            for (int[] dir : DIRS) {
              final int x = i + dir[0];
              final int y = j + dir[1];
              if (x < 0 || x == m || y < 0 || y == n)
                continue;
              next ^= 1 << (x * n + y);
            }
            if (next == 0)
              return step;
            if (seen.contains(next))
              continue;
            q.offer(next);
            seen.add(next);
          }
        }
      }
    }

    return -1;
  }

  private int getHash(int[][] mat, int m, int n) {
    int hash = 0;
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (mat[i][j] == 1)
          hash |= 1 << (i * n + j);
    return hash;
  }
}


C++ solution:
class Solution {
 public:
  int minFlips(vector<vector<int>>& mat) {
    const int m = mat.size();
    const int n = mat[0].size();
    const int hash = getHash(mat, m, n);
    if (hash == 0)
      return 0;

    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    queue<int> q{{hash}};
    unordered_set<int> seen{hash};

    for (int step = 1; !q.empty(); ++step) {
      for (int sz = q.size(); sz > 0; --sz) {
        const int curr = q.front();
        q.pop();
        for (int i = 0; i < m; ++i) {
          for (int j = 0; j < n; ++j) {
            int next = curr ^ 1 << (i * n + j);
            // Flie the four neighbors.
            for (const auto& [dx, dy] : kDirs) {
              const int x = i + dx;
              const int y = j + dy;
              if (x < 0 || x == m || y < 0 || y == n)
                continue;
              next ^= 1 << (x * n + y);
            }
            if (next == 0)
              return step;
            if (seen.contains(next))
              continue;
            q.push(next);
            seen.insert(next);
          }
        }
      }
    }

    return -1;
  }

 private:
  int getHash(const vector<vector<int>>& mat, int m, int n) {
    int hash = 0;
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (mat[i][j])
          hash |= 1 << (i * n + j);
    return hash;
  }
};