Talentd
FleetCode

1034. Coloring A Border

Medium51.8% acceptance3 companies

You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.

Two squares are called adjacent if they are next to each other in any of the 4 directions.

Two squares belong to the same connected component if they have the same color and they are adjacent.

The border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).

You should color the border of the connected component that contains the square grid[row][col] with color.

Return the final grid.

Example 1:

Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
Output: [[3,3],[3,2]]

Example 2:

Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3
Output: [[1,3,3],[2,3,3]]

Example 3:

Input: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2
Output: [[2,2,2],[2,1,2],[2,2,2]]

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • 1 <= grid[i][j], color <= 1000
  • 0 <= row < m
  • 0 <= col < n

Asked at 3 companies

Hints open one at a time

Hint 1
Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color.
21:34
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution

Similar problems

Island PerimeterEasy
Loading editor…
1class Solution:
2 def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
3
Starter codePython 3Spaces: 4
Examples
Input
[[1,1],[1,2]]
0
0
3
Input
[[1,2,2],[2,3,2]]
0
1
3
Input
[[1,1,1],[1,1,1],[1,1,1]]
1
1
2
Your code is saved on this device.Solution