1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
class Solution:
directs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def dfs(self, grid, i, j, origin_color, color, visited):
rows, cols = len(grid), len(grid[0])
for direct in self.directs:
new_i = i + direct[0]
new_j = j + direct[1]
# 下一个位置越界,则当前点在边界,对其进行着色
if new_i < 0 or new_i >= rows or new_j < 0 or new_j >= cols:
grid[i][j] = color
continue
# 如果访问过,则跳过
if visited[new_i][new_j]:
continue
# 如果下一个位置颜色与当前颜色相同,则继续搜索
if grid[new_i][new_j] == origin_color:
visited[new_i][new_j] = True
self.dfs(grid, new_i, new_j, origin_color, color, visited)
# 下一个位置颜色与当前颜色不同,则当前位置为连通区域边界,对其进行着色
else:
grid[i][j] = color
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
if not grid:
return grid
rows, cols = len(grid), len(grid[0])
visited = [[False for _ in range(cols)] for _ in range(rows)]
visited[row][col] = True
self.dfs(grid, row, col, grid[row][col], color, visited)
return grid
|