MediumNo. 1034
Coloring A Border — LeetCode 1034 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Depth-First Search, Breadth-First Search, Array, Matrix
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
- Output
- [[3,3],[3,2]]
Python solution
class Solution:
def colorBorder(
self, grid: List[List[int]], row: int, col: int, color: int
) -> List[List[int]]:
def dfs(i: int, j: int, c: int) -> None:
vis[i][j] = True
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
if not vis[x][y]:
if grid[x][y] == c:
dfs(x, y, c)
else:
grid[i][j] = color
else:
grid[i][j] = color
m, n = len(grid), len(grid[0])
vis = [[False] * n for _ in range(m)]
dfs(row, col, grid[row][col])
return gridComplexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1034. Coloring A Border is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0130 | Surrounded Regions | Medium |
| 0200 | Number of Islands | Medium |
| 0417 | Pacific Atlantic Water Flow | Medium |
| 0463 | Island Perimeter | Easy |
| 0529 | Minesweeper | Medium |
| 0695 | Max Area of Island | Medium |
Frequently asked questions
- How hard is LeetCode 1034. Coloring A Border?
LeetCode 1034. Coloring A Border is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1034. Coloring A Border?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 1034. Coloring A Border?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 1034. Coloring A Border cover?
LeetCode 1034. Coloring A Border is tagged Depth-First Search, Breadth-First Search, Array and Matrix on LeetCode.