Skip to content

1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix 👍

  • Time: $O(mn \cdot 2^{mn})$
  • Space: $O(2^{mn})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 dirs[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] : dirs) {
              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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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)
            # Flie the four neighbors.
            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