Approach
Depth-first search
For Minimum Number of Days to Disconnect Island, 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
- 52 lines of C++ from the credited upstream file 1568.cpp.
- The implementation visibly relies on sequence storage.
- 5 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 minDays(vector<vector<int>>& grid) {4 if (disconnected(grid))5 return 0;6 7 8 for (int i = 0; i < grid.size(); ++i)9 for (int j = 0; j < grid[0].size(); ++j)10 if (grid[i][j] == 1) {11 grid[i][j] = 0;12 if (disconnected(grid))13 return 1;14 grid[i][j] = 1;15 }16 17 18 return 2;19 }20 21 private:22 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};23 24 bool disconnected(const vector<vector<int>>& grid) {25 int islandsCount = 0;26 vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size()));27 for (int i = 0; i < grid.size(); ++i)28 for (int j = 0; j < grid[0].size(); ++j) {29 if (grid[i][j] == 0 || seen[i][j])30 continue;31 if (++islandsCount > 1)32 return true;33 dfs(grid, i, j, seen);34 }35 return islandsCount != 1;36 }37 38 void dfs(const vector<vector<int>>& grid, int i, int j,39 vector<vector<bool>>& seen) {40 seen[i][j] = true;41 for (const auto& [dx, dy] : kDirs) {42 const int x = i + dx;43 const int y = j + dy;44 if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())45 continue;46 if (grid[x][y] == 0 || seen[x][y])47 continue;48 dfs(grid, x, y, seen);49 }50 }51};52