Social feed~15 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-733dfs
A photo editor in a social feed app has a fill tool. A photo is a grid of shades, from 0 (black) to 255 (white). The user taps one pixel, and the tool paints the area around it with a new shade.
The area grows from the tapped pixel to its neighbours above, below, left and right. A neighbour joins when its shade differs by at most tol from the shade of the pixel it touches. Soft gradients are therefore filled, even when the far end is very different from the start.
Write gradient_fill(shades, row, col, tol, paint).
shades[r][c] is the shade of a pixel. The tapped pixel is (row, col).tol. The tapped pixel is always in the area.paint. Other pixels keep their shade.Input: shades = [[10,12,30,32,90],[11,14,33,60,91],[50,15,35,61,95],[52,16,70,62,96]], row = 0, col = 0, tol = 3, paint = 0
Output: [[0,0,30,32,90],[0,0,33,60,91],[50,0,35,61,95],[52,0,70,62,96]]A stack holds the pixels whose neighbours are still to be tried. Each row of the table is one pixel taken from the stack.
| Pixel taken | Shade | Neighbours that join |
|---|---|---|
| (0,0) | 10 | (1,0) shade 11, (0,1) shade 12 |
| (0,1) | 12 | (1,1) shade 14 |
| (1,1) | 14 | (2,1) shade 15 |
| (2,1) | 15 | (3,1) shade 16 |
| (3,1) | 16 | none |
| (1,0) | 11 | none |
The area has 6 pixels. Pixel (1,1) has shade 14, which is 4 away from the start, but it is only 2 away from its neighbour (0,1), so it joins.
Input: shades = [[5,5,9],[5,7,9]], row = 0, col = 0, tol = 0, paint = 1
Output: [[1,1,9],[1,7,9]]With tolerance 0, only pixels of the same shade join. This is the usual paint-bucket tool.
Input: shades = [[4]], row = 0, col = 0, tol = 2, paint = 4
Output: [[4]]The photo has one pixel, and the new shade is the same as the old one. The grid does not change.
1 ≤ rows, columns ≤ 400paint is between 0 and 2550 ≤ tol ≤ 255, 0 ≤ row < rows and 0 ≤ col < columnsA photo has up to 400 × 400 = 160,000 pixels. Sweeping the whole grid again and again until no pixel joins can need a sweep for every turn of a winding area, so tens of thousands of sweeps. A walk that visits each pixel once costs O(r c), about 640,000 neighbour checks.