Given an image as a grid of colors, a starting pixel (sr, sc) and a color, recolor the starting pixel and every pixel 4-directionally connected to it that has the same original color.
Same idea, iteratively: paint a pixel as soon as it is queued so it is never queued twice.
1function floodFill(image: number[][], sr: number, sc: number, color: number): number[][] {2const start = image[sr][sc];3if (start === color) return image;4image[sr][sc] = color;5const queue = [[sr, sc]];6while (queue.length) {7const [r, c] = queue.shift()!;8for (const [x, y] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]])9if (image[x]?.[y] === start) { image[x][y] = color; queue.push([x, y]); }10}11return image;12}
| 1 | 1 | 1 | 0 |
| 1 | 2 | 0 | 0 |
| 1 | 0 | 1 | 1 |
| 0 | 1 | 1 | 1 |
Paint (1, 1) and queue it.
Space: play/pause · ←/→: step