Recolor the Cross-Stitch

Easydepth-first searchAlso known as Flood Fill

You are planning a cross-stitch picture on squared paper. Each square holds a thread number, like 3 for sky blue or 7 for grass green. Halfway through, you decide one patch of sky should be a sunset orange instead.

A patch is every square you can reach from the one you tap by stepping up, down, left or right onto the same thread number. Squares that only touch at a corner are not part of it, and neither is a separate patch of the same color elsewhere on the paper.

Your task

Write recolorPatch(pattern, row, col, newColor). pattern is a grid of thread numbers. Change every square in the patch that contains pattern[row][col] to newColor, and return the grid.

Two squares are in the same patch if you can walk from one to the other through squares of that same thread number, moving only up, down, left or right. You may change pattern in place or build a new grid. If newColor is already the patch's color, nothing changes.

recolorPatch(pattern: int[][], row: int, col: int, newColor: int) → int[][]

Examples

Example 1
Input
pattern = [[3, 3, 5], [3, 5, 5], [5, 3, 3]]
row = 0
col = 0
newColor = 8
Output
[[8, 8, 5], [8, 5, 5], [5, 3, 3]]
Why

The tapped square holds 3. Its patch is the three 3s in the top-left corner. The two 3s in the bottom row also hold 3, but no up/down/left/right path of 3s joins them to the corner, so they stay 3.

Example 2
Input
pattern = [[1, 2], [2, 1]]
row = 0
col = 0
newColor = 4
Output
[[4, 2], [2, 1]]
Why

The two 1s touch only at a corner, so they are separate patches. Only the top-left square changes.

Constraints

  • 1 ≤ rows, cols ≤ 20
  • 0 ≤ pattern[r][c], newColor ≤ 99
  • 0 ≤ row < rows and 0 ≤ col < cols
Start with brute force

Recolor the tapped square, then sweep the whole grid again and again: any square with the old color that sits next to a recolored one gets recolored too. Stop when a full sweep changes nothing.

It works, but a patch shaped like a winding snake that doubles back against the sweep direction can grow by only a few squares per sweep. A 20 × 20 grid could need around a hundred sweeps of 400 squares each. A search that follows the patch directly touches each square once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code