Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Coloring A Border (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

You are given an m x n integers grid, and three integers row, col, and color. Each cell in the grid has a color value represented by an integer.

Two cells are adjacent if they share a side. Cells with the same color and connected through adjacent cells form a connected component.

Color the border of the connected component that includes the cell at grid[row][col] with the new color provided. The border of a connected component consists of cells that are either adjacent to a cell with a different color or lie on the boundary of the grid.

Return the modified grid after coloring the border.

Examples

Example 1:

  • Input: row = 1, col = 1, color = 3, grid =
[[1, 2, 2], 
 [2, 2, 2], 
 [1, 2, 1]]
  • Expected Output: [[1, 3, 3], [3, 2, 3], [1, 3, 1]]
Image
  • Justification: The connected component includes all cells. The border cells are colored with 1.

Example 2:

  • Input: row = 2, col = 0, color = 1, grid =
[[2, 2, 2], 
 [2, 2, 2], 
 [2, 2, 2]]
  • Expected Output: [[1, 1, 1], [1, 2, 1], [1, 1, 1]]
Image
  • Justification: The connected component includes all cells. The border cells are colored with 1.

Example 3:

  • Input: row = 1, col = 2, color = 4, grid =
[[1, 1, 1, 1], 
 [1, 1, 2, 2], 
 [1, 1, 2, 2]]
  • Expected Output: [[1, 1, 1, 1], [1, 1, 4, 4], [1, 1, 4, 4]]
Image
  • Justification: The connected component is the block of 2s. The border cells of this block are colored with 4.

Constraints:

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

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible