|
| 1 | +''' |
| 2 | +Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location. |
| 3 | +
|
| 4 | +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. |
| 5 | +
|
| 6 | +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). |
| 7 | +
|
| 8 | +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. |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3 |
| 13 | +Output: [[3, 3], [3, 2]] |
| 14 | +Example 2: |
| 15 | +
|
| 16 | +Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3 |
| 17 | +Output: [[1, 3, 3], [2, 3, 3]] |
| 18 | +Example 3: |
| 19 | +
|
| 20 | +Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2 |
| 21 | +Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]] |
| 22 | + |
| 23 | +
|
| 24 | +Note: |
| 25 | +
|
| 26 | +1 <= grid.length <= 50 |
| 27 | +1 <= grid[0].length <= 50 |
| 28 | +1 <= grid[i][j] <= 1000 |
| 29 | +0 <= r0 < grid.length |
| 30 | +0 <= c0 < grid[0].length |
| 31 | +1 <= color <= 1000 |
| 32 | +''' |
| 33 | + |
| 34 | +class Solution(object): |
| 35 | + def colorBorder(self, grid, r0, c0, color): |
| 36 | + """ |
| 37 | + :type grid: List[List[int]] |
| 38 | + :type r0: int |
| 39 | + :type c0: int |
| 40 | + :type color: int |
| 41 | + :rtype: List[List[int]] |
| 42 | + """ |
| 43 | + if not grid: |
| 44 | + return grid |
| 45 | + visited, border = [], [] |
| 46 | + m, n = len(grid), len(grid[0]) |
| 47 | + |
| 48 | + def dfs(r, c): |
| 49 | + if r < 0 or c < 0 or r >= m or c >= n or grid[r][c] != grid[r0][c0] or (r,c) in visited: |
| 50 | + return |
| 51 | + visited.append((r,c)) |
| 52 | + |
| 53 | + # check if the current row, col index is edge of the matrix |
| 54 | + # if not then check adjacent cells doesnt have same value as grid[r0][c0] then add in border |
| 55 | + if (r == 0 or c == 0 or r == m-1 or c == n-1 or |
| 56 | + (r+1 < m and grid[r+1][c] != grid[r0][c0]) or |
| 57 | + (r-1 >= 0 and grid[r-1][c] != grid[r0][c0]) or |
| 58 | + (c+1 < n and grid[r][c+1] != grid[r0][c0]) or |
| 59 | + (c-1 >= 0 and grid[r][c-1] != grid[r0][c0])): |
| 60 | + border.append((r,c)) |
| 61 | + dfs(r-1, c) |
| 62 | + dfs(r+1, c) |
| 63 | + dfs(r, c-1) |
| 64 | + dfs(r, c+1) |
| 65 | + |
| 66 | + dfs(r0, c0) |
| 67 | + for (x, y) in border: |
| 68 | + grid[x][y] = color |
| 69 | + return grid |
0 commit comments