Coloring A Border
class Solution:
def colorBorder(self, A: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]:
if not A or not A[0]:
return A
d = [-1, 0, 1, 0, -1]
n, m = len(A), len(A[0])
bclr = A[r0][c0]
def dfs(x,y):
nonlocal bclr
if A[x][y] == -bclr:
return
A[x][y] = -bclr
cnt = 0
for nx, ny in [(x + d[k], y + d[k + 1]) for k in range(4)]:
if not (0 <= nx < n and 0 <= ny < m and abs(A[nx][ny]) == bclr):
continue
cnt += 1 #正负色都行,所以上面是abs(A[nx][ny]) == bclr
if A[nx][ny] == bclr: dfs(nx,ny)#正色才能继续dfs
if cnt == 4:
A[x][y] = bclr
dfs(r0,c0)
for i in range(n):
for j in range(m):
if A[i][j] < 0:
A[i][j] = color
return ALast updated