Description
Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.
Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.
The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).
Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.
Note:
- 1 <= grid.length <= 50
- 1 <= grid[0].length <= 50
- 1 <= grid[i][j] <= 1000
- 0 <= r0 < grid.length
- 0 <= c0 < grid[0].length
- 1 <= color <= 1000
Example
Example 1:
Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
Output: [[3, 3], [3, 2]]
Example 2:
Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
Output: [[1, 3, 3], [2, 3, 3]]
Example 3:
Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]
Submissions
首先这道题是指找出给定位置(r0,c0)的连通分量,并将边界赋为给定color。因此解题思路主要为判断给定位置四个边界,并递归向外进行扩展判断,如果四个边不全,则进行上色。
实现代码如下:
class Solution:
def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]:
old_color = grid[r0][c0]
new_color = color
n, m = len(grid), len(grid[0])
seen = set()
def dfs(i,j):
if (i,j) in seen: return True
if not (0<=i<n and 0<=j<m and grid[i][j] == old_color):
return False
seen.add((i,j))
if dfs(i+1, j) + dfs(i-1, j) + dfs(i, j+1) + dfs(i, j-1) < 4
grid[i][j] = new_color
return True
dfs(r0, c0)
return grid