Coloring A Border LeetCode solution in Python

1
# Runtime: 136 ms (Top 91.96%) | Memory: 14.4 MB (Top 28.67%)
2

3

4
class Solution:
5
def colorBorder(
6
self, grid: List[List[int]], row: int, col: int, color: int
7
) -> List[List[int]]:
8

9
rows, cols = len(grid), len(grid[0])
10
border_color = grid[row][col]
11
border = []
12

13
# Check if a node is a border node or not
14
def is_border(r, c):
15
if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:
16
return True
17

18
for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
19
nr, nc = r + dr, c + dc
20
if grid[nr][nc] != border_color:
21
return True
22
return False
23

24
def dfs(r, c):
25
if (
26
r < 0
27
or c < 0
28
or r == rows
29
or c == cols
30
or (r, c) in visited
31
or grid[r][c] != border_color
32
):
33
return
34
visited.add((r, c))
35

36
if is_border(r, c):
37
border.append((r, c))
38

39
dfs(r + 1, c)
40
dfs(r - 1, c)
41
dfs(r, c + 1)
42
dfs(r, c - 1)
43

44
visited = set()
45
dfs(row, col)
46
for r, c in border:
47
grid[r][c] = color
48
return grid

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0