An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor.
Return the modified image after performing the flood fill.
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1)
(i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel
(i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
Output: [[2,2,2],[2,2,2]]
처음으로 접하는 이 개념을...DFS를 찾아보기만 해서는 어떻게 풀어야 할지 감이 안 잡혀서, 풀이를 하나하나 뜯어보며 풀이방식을 이해하는 것으로 첫번째 DFS풀이를 대신하기로 했다.
/**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} newColor
* @return {number[][]}
*/
var floodFill = function(image, sr, sc, newColor) {
const startingColor = image[sr][sc];
image[sr][sc] = newColor;
const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
const helper = (sr, sc) => {
for (let direction of directions) {
const row = sr + d[0];
const col = sc + d[1];
if (
row >= 0 && row < image.length && col >= 0 && col < image[row].length &&
image[row][col] === startingColor && image[row][col] !== newColor
) {
image[row][col] = newColor;
helper(row, col);
}
}
};
helper(sr, sc);
return image;
};
var floodFill = function(image, sr, sc, newColor) {
let directions = [ [-1, 0], [1,0], [0, -1], [0, 1] ];
let height = image.length;
let width = image[0].length;
fillNeighbour( [[sr,sc]], image[sr][sc] , newColor );
return image;
function fillNeighbour(queue, oldColor, newColor) {
while(queue.length > 0){
let [a, b] = queue.shift();
image[a][b] = newColor;
directions.map((direction) => {
let [m,n] = direction;
let x = a+m;
let y = b+n;
if( x >=0 && y >= 0 && x < height && y < width
&& image[x][y] === oldColor && image[x][y] !== newColor ) {
queue.push([x, y]);
}
});
}
}
};