Approach
Breadth-first search
For Minimum Number of Flips to Convert Binary Matrix to Zero Matrix, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 53 lines of C++ from the credited upstream file 1284.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 7 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minFlips(vector<vector<int>>& mat) {4 const int m = mat.size();5 const int n = mat[0].size();6 const int hash = getHash(mat, m, n);7 if (hash == 0)8 return 0;9 10 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};11 queue<int> q{{hash}};12 unordered_set<int> seen{hash};13 14 for (int step = 1; !q.empty(); ++step) {15 for (int sz = q.size(); sz > 0; --sz) {16 const int curr = q.front();17 q.pop();18 for (int i = 0; i < m; ++i) {19 for (int j = 0; j < n; ++j) {20 int next = curr ^ 1 << (i * n + j);21 22 for (const auto& [dx, dy] : kDirs) {23 const int x = i + dx;24 const int y = j + dy;25 if (x < 0 || x == m || y < 0 || y == n)26 continue;27 next ^= 1 << (x * n + y);28 }29 if (next == 0)30 return step;31 if (seen.contains(next))32 continue;33 q.push(next);34 seen.insert(next);35 }36 }37 }38 }39 40 return -1;41 }42 43 private:44 int getHash(const vector<vector<int>>& mat, int m, int n) {45 int hash = 0;46 for (int i = 0; i < m; ++i)47 for (int j = 0; j < n; ++j)48 if (mat[i][j])49 hash |= 1 << (i * n + j);50 return hash;51 }52};53