Approach
Depth-first search
For Making a Large 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
- 47 lines of Python from the credited upstream file making-a-large-island.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.
123 4 5class Solution(object):6 def largestIsland(self, grid):7 """8 :type grid: List[List[int]]9 :rtype: int10 """11 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]12 13 def dfs(r, c, index, grid):14 if not (0 <= r < len(grid) and15 0 <= c < len(grid[0]) and16 grid[r][c] == 1):17 return 018 result = 119 grid[r][c] = index20 for d in directions:21 result += dfs(r+d[0], c+d[1], index, grid)22 return result23 24 area = {}25 index = 226 for r in xrange(len(grid)):27 for c in xrange(len(grid[r])):28 if grid[r][c] == 1:29 area[index] = dfs(r, c, index, grid)30 index += 131 32 result = max(area.values() or [0])33 for r in xrange(len(grid)):34 for c in xrange(len(grid[r])):35 if grid[r][c] == 0:36 seen = set()37 for d in directions:38 nr, nc = r+d[0], c+d[1]39 if not (0 <= nr < len(grid) and40 0 <= nc < len(grid[0]) and41 grid[nr][nc] > 1):42 continue43 seen.add(grid[nr][nc])44 result = max(result, 1 + sum(area[i] for i in seen))45 return result46 47