Approach
Depth-first search
For Coloring A Border, 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
- 39 lines of Python from the credited upstream file 1034.py.
- The implementation visibly relies on sequence storage.
- 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 colorBorder(3 self,4 grid: list[list[int]],5 r0: int,6 c0: int,7 color: int8 ) -> list[list[int]]:9 def dfs(i: int, j: int, startColor: int) -> None:10 if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):11 return12 if grid[i][j] != startColor:13 return14 15 grid[i][j] = -startColor16 dfs(i + 1, j, startColor)17 dfs(i - 1, j, startColor)18 dfs(i, j + 1, startColor)19 dfs(i, j - 1, startColor)20 21 22 if i == 0 or i == len(grid) - 1 or j == 0 or j == len(grid[0]) - 1:23 return24 25 if (abs(grid[i + 1][j]) == startColor and26 abs(grid[i - 1][j]) == startColor and27 abs(grid[i][j + 1]) == startColor and28 abs(grid[i][j - 1]) == startColor):29 grid[i][j] = startColor30 31 dfs(r0, c0, grid[r0][c0])32 33 for i, row in enumerate(grid):34 for j, num in enumerate(row):35 if num < 0:36 grid[i][j] = color37 38 return grid39