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
- 45 lines of Python from the credited upstream file 1568.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit 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 def minDays(self, grid: list[list[int]]) -> int:3 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))4 m = len(grid)5 n = len(grid[0])6 7 def dfs(grid: list[list[int]], i: int, j: int, seen: set[tuple[int, int]]):8 seen.add((i, j))9 for dx, dy in DIRS:10 x = i + dx11 y = j + dy12 if x < 0 or x == m or y < 0 or y == n:13 continue14 if grid[x][y] == 0 or (x, y) in seen:15 continue16 dfs(grid, x, y, seen)17 18 def disconnected(grid: list[list[int]]) -> bool:19 islandsCount = 020 seen = set()21 for i in range(m):22 for j in range(n):23 if grid[i][j] == 0 or (i, j) in seen:24 continue25 if islandsCount > 1:26 return True27 islandsCount += 128 dfs(grid, i, j, seen)29 return islandsCount != 130 31 if disconnected(grid):32 return 033 34 35 for i in range(m):36 for j in range(n):37 if grid[i][j] == 1:38 grid[i][j] = 039 if disconnected(grid):40 return 141 grid[i][j] = 142 43 44 return 245