MediumNo. 1034

Coloring A Border — LeetCode 1034 Python Solution

Topics
Depth-First Search, Breadth-First Search, Array, Matrix
Reading time
4 min

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

PythonSolution
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 grid

Complexity

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

Related problems
No.ProblemDifficulty
0130Surrounded RegionsMedium
0200Number of IslandsMedium
0417Pacific Atlantic Water FlowMedium
0463Island PerimeterEasy
0529MinesweeperMedium
0695Max Area of IslandMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.