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
- 50 lines of Java from the credited upstream file 1284.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 int minFlips(int[][] mat) {3 final int m = mat.length;4 final int n = mat[0].length;5 final int hash = getHash(mat, m, n);6 if (hash == 0)7 return 0;8 9 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};10 Queue<Integer> q = new ArrayDeque<>(List.of(hash));11 Set<Integer> seen = new HashSet<>(Arrays.asList(hash));12 13 for (int step = 1; !q.isEmpty(); ++step) {14 for (int sz = q.size(); sz > 0; --sz) {15 final int curr = q.poll();16 for (int i = 0; i < m; ++i) {17 for (int j = 0; j < n; ++j) {18 int next = curr ^ 1 << (i * n + j);19 20 for (int[] dir : DIRS) {21 final int x = i + dir[0];22 final int y = j + dir[1];23 if (x < 0 || x == m || y < 0 || y == n)24 continue;25 next ^= 1 << (x * n + y);26 }27 if (next == 0)28 return step;29 if (seen.contains(next))30 continue;31 q.offer(next);32 seen.add(next);33 }34 }35 }36 }37 38 return -1;39 }40 41 private int getHash(int[][] mat, int m, int n) {42 int hash = 0;43 for (int i = 0; i < m; ++i)44 for (int j = 0; j < n; ++j)45 if (mat[i][j] == 1)46 hash |= 1 << (i * n + j);47 return hash;48 }49}50