Coloring A Border — LeetCode 1034 Python Solution
MediumDepth-First SearchBreadth-First SearchArrayMatrix
- Problem
- #1034
- Pattern
- Matrix and Grid
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
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
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.