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 sunset orange.

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

Your task

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

Two squares are in the same patch if you can walk between them through squares of that 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, and its patch is the three 3s in the top-left corner. The bottom row's 3s have no up/down/left/right path of 3s 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 grid again and again, recoloring any old-color square next to a recolored one, until a sweep changes nothing.

It works, but a winding, snake-shaped patch that doubles back against the sweep direction can grow only a few squares per sweep: a 20 × 20 grid could need around a hundred sweeps of 400 squares. A search that follows the patch 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