#1034
Coloring A Border
MediumArrayDepth-First SearchBreadth-First SearchMatrixDepth-First SearchGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m * n) |
| Space | O(m * n) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
The optimal solution uses a similar DFS approach but optimizes the border detection by marking cells during the DFS traversal. This reduces the need for a separate pass to identify borders, making it more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS to explore the connected component starting from grid[row][col].
- 2Step 2: During the DFS, check if a cell is a border cell and mark it accordingly.
- 3Step 3: After the DFS completes, color all marked border cells with the new color.
solution.py33 lines
1# Full working Python code
2from collections import deque
3
4def colorBorder(grid, row, col, color):
5 m, n = len(grid), len(grid[0])
6 original_color = grid[row][col]
7 visited = [[False] * n for _ in range(m)]
8 border = set()
9
10 def is_border(r, c):
11 if r < 0 or r >= m or c < 0 or c >= n:
12 return True
13 return grid[r][c] != original_color
14
15 def dfs(r, c):
16 if visited[r][c]:
17 return
18 visited[r][c] = True
19 if is_border(r, c):
20 border.add((r, c))
21 for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
22 nr, nc = r + dr, c + dc
23 if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == original_color:
24 dfs(nr, nc)
25 elif is_border(nr, nc):
26 border.add((r, c))
27
28 dfs(row, col)
29
30 for r, c in border:
31 grid[r][c] = color
32
33 return gridℹ
Complexity note: The time complexity remains O(m * n) due to the need to traverse the entire grid. The space complexity is also O(m * n) due to the visited array and border set.
- 1Understanding connected components is crucial.
- 2Identifying border cells efficiently can reduce unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.