Problem 1034

Abstract / Summary

Given a grid and a coordinate, change the color of all connected cells sharing the same initial color as the given cell except the given cell itself.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1034.py

class Solution:
    def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
        width  = len(grid[0])
        height = len(grid)

        # return color at x,y or -1 if out of bounds
        get = lambda x, y: grid[y][x] if 0 <= x < width and 0 <= y < height else -1

        todo   = [ [ col, row ] ]
        before = grid[row][col] # color used before painting it over
        border = set()
        seen   = set()
        while todo:
            x, y = todo.pop()
            if (x, y) in seen:
                continue
            seen.add((x, y))

            same = 0 # neighbors with same color
            if before == get(x - 1, y):
                todo.append((x - 1, y))
                same += 1
            if before == get(x, y - 1):
                todo.append((x, y - 1))
                same += 1
            if before == get(x + 1, y):
                todo.append((x + 1, y))
                same += 1
            if before == get(x, y + 1):
                todo.append((x, y + 1))
                same += 1

            # border if not fully surrounded by the same color
            if same < 4:
                border.add((x, y))

        # paint the border
        for x, y in border:
            grid[y][x] = color
        return grid
40 lines | 1342 bytes | submitted December 20, 2023 | GitHub   15% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Depth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The colorBorder method receives a 2-dimensional integer matrix grid, a starting cell identified by (row, col), and a target color. It recolors only the cells that lie on the outer edge of the contiguous region that shares the original color of the starting cell. The algorithm walks the region, records which cells are on the perimeter, and finally paints those perimeter cells with the new color, returning the modified grid.

Initialization and Helper Function

The first part of the code extracts the dimensions of the matrix, defines a small helper to safely read a cell value, and creates the data structures needed for the search.

width  = len(grid[0])
height = len(grid)

# return color at x,y or -1 if out of bounds
get = lambda x, y: grid[y][x] if 0 <= x < width and 0 <= y < height else -1

todo   = [ [ col, row ] ]
before = grid[row][col]          # original color of the component
border = set()
seen   = set()
  • width and height give constant-time access to the matrix bounds.
  • The get lambda abstracts boundary checking; any coordinate outside the matrix yields -1, a sentinel that never matches a legitimate color.
  • todo is a stack that drives the depth-first traversal, seeded with the starting cell.
  • before stores the color that defines the component.
  • border accumulates cells that belong to the outer edge, while seen prevents revisiting cells.

Depth-First Search Loop

The core of the algorithm is a loop that processes cells until the stack is empty. For each cell it first checks whether the cell has already been visited; if not, it marks it as seen and inspects its four orthogonal neighbours.

while todo:
    x, y = todo.pop()
    if (x, y) in seen:
        continue
    seen.add((x, y))

    same = 0                     # count of neighbours sharing the original color
    if before == get(x - 1, y):
        todo.append((x - 1, y))
        same += 1
    if before == get(x, y - 1):
        todo.append((x, y - 1))
        same += 1
    if before == get(x + 1, y):
        todo.append((x + 1, y))
        same += 1
    if before == get(x, y + 1):
        todo.append((x, y + 1))
        same += 1

    # border if not fully surrounded by the same color
    if same < 4:
        border.add((x, y))

During each iteration:

  • The cell is removed from todo using pop, which yields a last-in-first-out order, implementing an explicit stack and avoiding recursion.
  • The seen set guarantees that each coordinate is processed at most once, eliminating duplicate work.
  • For each of the four directions the helper get is invoked; a match with before both enqueues the neighbour for later processing and increments same.
  • If fewer than four neighbours share the original color, the current cell lies on the perimeter and is added to border.

Border Collection

The border set stores unique perimeter coordinates. Because a cell may be discovered from multiple neighbours, using a set automatically deduplicates entries without extra checks.

if same < 4:
    border.add((x, y))

Painting Phase

After the traversal finishes, the algorithm iterates over the collected border cells and overwrites their values with the requested new color.

for x, y in border:
    grid[y][x] = color
return grid

The final grid is returned directly, reflecting the recolored border while leaving interior cells untouched.

Edge Cases Handled

The implementation gracefully manages several boundary conditions:

  • Out-of-bounds neighbours - The get lambda returns -1 for any coordinate outside the matrix. Since -1 never equals a legitimate cell color, such neighbours are treated as mismatches, causing the cell to be classified as a border when it touches the matrix edge.
  • Single-cell component - When the starting cell has no neighbours of the same color, same remains 0, the cell is added to border, and it is recolored, correctly handling isolated cells.
  • Component touching the grid border - Cells on the outermost rows or columns automatically have fewer than four matching neighbours because the out-of-bounds checks yield -1. Consequently, they are marked as border cells, ensuring the algorithm respects the physical edge of the grid.
  • Original color equals target color - The algorithm still performs the search and may add cells to border, but the final assignment writes the same value back. This does not affect correctness and avoids a premature shortcut that could miss border detection.
  • Non-rectangular input - The code assumes a rectangular grid (all rows have equal length). The initial width is derived from the first row, and the helper respects those dimensions throughout the traversal.

Performance Optimizations Observed

The code incorporates several choices that keep the execution efficient:

  • Explicit stack instead of recursion - Using a list as a stack (todo) avoids the overhead of Python’s call stack and prevents potential recursion depth limits on large components.
  • Constant-time boundary check via lambda - The get helper centralizes the bounds test, eliminating repetitive conditional logic in each neighbour inspection and allowing the compiler to inline the simple expression.
  • Set-based deduplication - Both seen and border are implemented as hash sets, providing O(1) average-time membership tests and insertions. This ensures each cell is examined once and each border cell is painted once, regardless of how many times it is discovered from different neighbours.
  • Early continuation for already visited cells - The if (x, y) in seen: continue guard stops further processing of duplicate entries immediately, saving the cost of neighbour checks for those cells.
  • Minimal auxiliary data - Only four small containers (todo, seen, border, and the lambda) are allocated, keeping memory usage proportional to the size of the component rather than the entire grid.

These design decisions collectively yield a solution that scales linearly with the number of cells belonging to the connected component, while keeping overhead low for both time and memory.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big sheet of graph paper covered in colorful blocks. You want to pick one colored blob and draw a special outline around its edges.

First, the computer looks at the specific block where you started and remembers what color it is. It starts a little treasure hunt by visiting every block that matches that color and is touching the first one. It keeps a list of all these blocks so it does not get lost or visit the same spot twice.

For every block the computer visits, it looks at the four neighbors right next to it. If a neighbor is the same color, the computer hops over to check that one too. If a block is missing a neighbor of the same color or is sitting on the very edge of the paper, it means the block is part of the outside boundary. The computer keeps a secret diary of all these edge blocks.

Once the treasure hunt is finished and every connected block has been checked, the computer goes back to that secret diary. It takes all the blocks on the list and paints them the new color you chose. Now you have a beautiful colored border protecting your shape.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.12 | σ = 0.85

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
lkwq007 Python
lzl124631x C++
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
lzl124631x C++
suxrobGM C#
30 links | 16 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

20 solutions   December 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality