Approach
Depth-first search
For Minimum Operations to Remove Adjacent Ones in Matrix, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 48 lines of Java from the credited upstream file 2123.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 minimumOperations(int[][] grid) {3 final int m = grid.length;4 final int n = grid[0].length;5 int ans = 0;6 int[][] seen = new int[m][n];7 int[][] match = new int[m][n];8 Arrays.stream(match).forEach(A -> Arrays.fill(A, -1));9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (grid[i][j] == 1 && match[i][j] == -1) {13 final int sessionId = i * n + j;14 seen[i][j] = sessionId;15 if (dfs(grid, i, j, sessionId, seen, match))16 ++ans;17 }18 19 return ans;20 }21 22 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};23 24 private boolean dfs(final int[][] grid, int i, int j, int sessionId, int[][] seen,25 int[][] match) {26 final int m = grid.length;27 final int n = grid[0].length;28 29 for (int[] dir : DIRS) {30 final int x = i + dir[0];31 final int y = j + dir[1];32 if (x < 0 || x == m || y < 0 || y == n)33 continue;34 if (grid[x][y] == 0 || seen[x][y] == sessionId)35 continue;36 seen[x][y] = sessionId;37 if (match[x][y] == -1 ||38 dfs(grid, match[x][y] / n, match[x][y] % n, sessionId, seen, match)) {39 match[x][y] = i * n + j;40 match[i][j] = x * n + y;41 return true;42 }43 }44 45 return false;46 }47}48