Skip to main content

Coloring A Border - Solution & Explanation

MediumArrayDepth-First SearchBreadth-First SearchMatrix19 min readAsked at: Microsoft, Booking.com, Google
Practice this problem

Problem Statement

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

Approach Overview

Problem Overview: You are given a grid of colors and a starting cell. The task is to find the connected component that shares the same color as the starting cell and repaint only its border cells with a new color. A border cell is one that touches the grid boundary or has at least one neighboring cell with a different color.

Approach 1: Depth-First Search (DFS) Traversal (Time: O(m*n), Space: O(m*n))

This approach treats the grid like a graph where each cell connects to its four neighbors. Starting from (row, col), run a DFS to visit all cells belonging to the same connected component. While exploring neighbors, determine whether the current cell lies on the border by checking if it touches the grid boundary or if any adjacent cell has a different color. Border cells are collected in a list (or marked temporarily) and recolored after traversal. DFS works well here because recursion naturally explores connected regions, making it easy to track visited cells and inspect neighbors. The extra space comes from the recursion stack and the visited structure.

DFS solutions commonly rely on a visited matrix or temporarily marking cells to avoid revisiting. Each cell is processed at most once, giving linear complexity relative to the grid size. If you want to strengthen your understanding of recursive grid traversal, review Depth-First Search and common patterns in matrix problems.

Approach 2: Breadth-First Search (BFS) Traversal (Time: O(m*n), Space: O(m*n))

BFS solves the same connected-component problem using a queue instead of recursion. Begin by pushing the starting cell into a queue and expanding level by level. For each cell, inspect the four directions and enqueue neighbors with the same original color that have not been visited. During processing, check whether the current cell touches the boundary or has a neighbor with a different color. If so, mark it as a border candidate.

After BFS finishes exploring the component, update the stored border cells with the new color. BFS is iterative and avoids recursion depth issues, which can be helpful for very large grids. The algorithm still visits each cell once and performs constant neighbor checks, resulting in O(m*n) time complexity and O(m*n) space due to the queue and visited tracking. This pattern is common in Breadth-First Search problems involving grid components.

Recommended for interviews: Both DFS and BFS are accepted optimal solutions with identical complexity. Interviewers usually expect a DFS implementation because it is shorter and highlights your ability to reason about connected components in a grid. Showing the BFS variant demonstrates understanding of traversal tradeoffs and queue-based graph exploration.

Approach 1: Depth-First Search (DFS) Approach

This approach uses a depth-first search (DFS) to explore the grid and find the connected component starting from the given cell. We'll use DFS to identify all cells belonging to the same color as the starting cell. As we perform DFS, we mark cells that are potential borders if they are on the edge of the grid or adjacent to a different color. Finally, we change the color of these border cells to the specified new color.

We start by initializing a matrix to keep track of visited cells and a list to store border cells. Using a DFS function, we recursively visit each cell in the connected component. We mark a cell as a border if it is adjacent to a cell of a different color or is at the grid's edge. After identifying all border cells, we change their color to the new color.

Code

Python

Java

C++

C

JavaScript

Complexity

Time Complexity: O(M*N) where M and N are the dimensions of the grid, because we potentially visit all cells.
Space Complexity: O(M*N) for the visited matrix and border cells list for storing the recursive call stack.

Try this approach in the editor →

Approach 2: Breadth-First Search (BFS) Approach

This approach employs a breadth-first search (BFS) to explore the grid starting from the specified cell. BFS is helpful because it processes nodes at the current 'depth' level fully before moving on to the nodes at the next depth level, making it easy to track border cells by checking neighbors first.

In this solution, we use a queue to perform BFS, starting from the given cell. As we process each cell, we determine if it is a border by checking adjacent cells. If it's a border, it's added to the 'borders' list. Finally, we change the color of all border cells to the specified color.

Code

Python

Java

C++

C#

JavaScript

Complexity

Time Complexity: O(M*N), processing each grid cell.
Space Complexity: O(M*N) using the queue and storing borders.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Depth-First Search (DFS) Approach

Time Complexity: O(M*N) where M and N are the dimensions of the grid, because we potentially visit all cells.
Space Complexity: O(M*N) for the visited matrix and border cells list for storing the recursive call stack.

Breadth-First Search (BFS) Approach

Time Complexity: O(M*N), processing each grid cell.
Space Complexity: O(M*N) using the queue and storing borders.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Depth-First Search (DFS)O(m*n)O(m*n)Preferred for interviews and recursive grid traversal problems
Breadth-First Search (BFS)O(m*n)O(m*n)Useful when avoiding recursion depth or when iterative traversal is preferred

Video Solution

Coloring a border || Leetcode • Pepcoding • 43,397 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Coloring A Border easy or hard?
Coloring A Border is rated Medium on LeetCode. The challenge comes from correctly identifying border cells while traversing a connected component and ensuring that internal cells remain unchanged. Strong familiarity with BFS or DFS on matrices makes the problem straightforward.
Coloring A Border Python/Java solution
Python and Java implementations typically follow the same logic: run DFS or BFS from the starting cell, track visited cells, detect borders by checking neighbors, and recolor those border cells. The algorithm maintains O(m*n) time complexity and O(m*n) auxiliary space.
How to solve Coloring A Border in O(n)?
Treat the grid as a graph and perform a DFS or BFS from the starting cell. Track visited cells and check four-directional neighbors to determine if a cell is on the boundary of the component. Store border cells separately and recolor them after traversal. The algorithm processes each cell once, giving O(m*n) time complexity.
What is the best approach for Coloring A Border?
The optimal solution uses either Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse the connected component starting from the given cell. During traversal, each cell checks its four neighbors to determine whether it lies on the component boundary. Border cells are recolored after the traversal completes. Both approaches run in O(m*n) time.
Is Coloring A Border asked at Google/Amazon/Meta?
Grid traversal and connected component problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variations involving BFS or DFS on matrices are common because they test graph fundamentals, boundary detection, and careful state tracking.
What data structure is used in Coloring A Border?
The solution primarily uses graph traversal structures. DFS implementations rely on recursion or an explicit stack, while BFS uses a queue. A visited matrix or marking technique is also required to avoid revisiting cells in the same connected component.
What is the time complexity of Coloring A Border?
The time complexity is O(m*n), where m and n are the grid dimensions. Each cell in the connected component is visited at most once, and every visit checks four neighbors. This keeps the work proportional to the total number of cells in the grid.

Ready to solve this problem?

Practice Coloring A Border with our built-in code editor and test cases.

Practice on FleetCode