Approach
Depth-first search
For Number of Enclaves, 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
- 33 lines of C++ from the credited upstream file 1020.cpp.
- The implementation visibly relies on sequence storage.
- 2 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:3 int numEnclaves(vector<vector<int>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 7 8 for (int i = 0; i < m; ++i)9 for (int j = 0; j < n; ++j)10 if (i * j == 0 || i == m - 1 || j == n - 1)11 if (grid[i][j] == 1)12 dfs(grid, i, j);13 14 return accumulate(grid.begin(), grid.end(), 0,15 [](int acc, const vector<int>& row) {16 return acc + ranges::count(row, 1);17 });18 }19 20 private:21 void dfs(vector<vector<int>>& grid, int i, int j) {22 if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())23 return;24 if (grid[i][j] == 0)25 return;26 grid[i][j] = 0;27 dfs(grid, i + 1, j);28 dfs(grid, i - 1, j);29 dfs(grid, i, j + 1);30 dfs(grid, i, j - 1);31 };32};33