Leetcode-1284

Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include <queue>

const int INF = 0x3fff'ffff;

class Solution {    
public:
    int minFlips(std::vector<std::vector<int>>& mat) {
        int m = mat.size();
        int n = mat[0].size();
        if (m * n == 1) {
            return mat[0][0];
        }
        if (m * n == 2) {
            if (mat[0][0] == mat.back().back()) {
                return mat[0][0];
            }
            return -1;
        }
        if (m * n == 4) {
            int a = mat[0][0] + mat[0][1] + mat[1][0] + mat[1][1];
            if (a != 1) {
                return a;
            }
            return 3;
        }
        
        int M = m * n;
        std::vector<int> dist((1 << M), INF);
        std::vector<int> mask(M, 0);
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < M; ++j) {
                mask[i] *= 2;
                if (i / n == j / n && std::abs(i - j) < 2) {
                    ++mask[i];
                }
                else if (!(i - j - n) || !(i - j + n)) {
                    ++mask[i];
                }
            }
        }
        
        int start = 0;
        for (auto& row : mat) {
            for (auto& y : row) {
                start *= 2;
                start += y;
            }
        }
        dist[start] = 0;
        
        std::queue<int> q;
        q.push(start);
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (auto& m : mask) {
                int v = u ^ m;
                if (v == 0) {
                    return dist[u] + 1;
                }
                if (dist[v] != INF) {
                    continue;
                }
                dist[v] = dist[u] + 1;
                q.push(v);
            }
        }
        
        return -1;
    }
};

Leetcode-1284

Licensed under CC BY-NC-SA 4.0