|
| 1 | +/** |
| 2 | + * 733. Flood Fill |
| 3 | + * https://leetcode.com/problems/flood-fill/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * An image is represented by an m x n integer grid image where image[i][j] represents |
| 7 | + * the pixel value of the image. |
| 8 | + * |
| 9 | + * You are also given three integers sr, sc, and newColor. You should perform a flood |
| 10 | + * fill on the image starting from the pixel image[sr][sc]. |
| 11 | + * |
| 12 | + * To perform a flood fill, consider the starting pixel, plus any pixels connected |
| 13 | + * 4-directionally to the starting pixel of the same color as the starting pixel, |
| 14 | + * plus any pixels connected 4-directionally to those pixels (also with the same color), |
| 15 | + * and so on. Replace the color of all of the aforementioned pixels with newColor. |
| 16 | + * |
| 17 | + * Return the modified image after performing the flood fill. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[][]} image |
| 22 | + * @param {number} sr |
| 23 | + * @param {number} sc |
| 24 | + * @param {number} newColor |
| 25 | + * @return {number[][]} |
| 26 | + */ |
| 27 | +var floodFill = function(image, sr, sc, newColor) { |
| 28 | + fill(image, sr, sc, image[sr][sc], newColor); |
| 29 | + return image; |
| 30 | +}; |
| 31 | + |
| 32 | +function fill(image, x, y, initialColor, newColor) { |
| 33 | + if (image[x] && image[x][y] === initialColor && initialColor !== newColor) { |
| 34 | + image[x][y] = newColor; |
| 35 | + [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] |
| 36 | + .forEach(([x, y]) => fill(image, x, y, initialColor, newColor)); |
| 37 | + } |
| 38 | +} |
0 commit comments