LeetCode - Flood Fill (Javascript)

타겟 넘버와 연결되어 있는 요소들을 모두 새로운 색(숫자)으로 변환시키는 문제였다.

문제 설명

뭐 대충, 테이블이 주어지고, 타겟 넘버의 위치(행과 열), 그리고 바꿀 색깔(숫자)를 인자에 담아 보내준다는 뜻이다.

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 srsc, 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.

Example 1:

타겟 넘버인 가운데(1,1)과 연결된 숫자들(동일한 숫자여야 함) → 새로운 색으로 칠해줌 (숫자 변경)

타겟 넘버인 가운데(1,1)과 연결된 숫자들(동일한 숫자여야 함) → 새로운 색으로 칠해줌 (숫자 변경)

1
2
3
4
5
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.

Example 2:

1
2
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
Output: [[2,2,2],[2,2,2]]

소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function floodFill(image, sr, sc, newColor) {
const answer = image;
const targetNum = image[sr][sc];
const maxRow = image.length;
const maxColumn = image[0].length;
let visited = {};
let idx;
function traverse(r, c) {
idx = r.toString() + c.toString();
if (visited[idx]) return;
visited[idx] = true;
const currentNode = image[r][c];
if (currentNode !== targetNum) return;
answer[r][c] = newColor;
if (r - 1 >= 0 && c >= 0 && c < maxColumn) traverse(r - 1, c);
if (r >= 0 && r < maxRow && c + 1 < maxColumn) traverse(r, c + 1);
if (r + 1 < maxRow && c >= 0 && c < maxColumn) traverse(r + 1, c);
if (r >= 0 && r < maxRow && c - 1 >= 0) traverse(r, c - 1);
}
traverse(sr, sc);
return answer;
}

Author

Hoonjoo

Posted on

2022-03-24

Updated on

2022-03-24

Licensed under

Comments