var floodFill = function (image, sr, sc, newColor) {
let oldColor = image[sr][sc];
DFS(image, sr, sc, oldColor, newColor);
return image;
};
var DFS = (image, x, y, oldColor, newColor) => {
if (
// ์ฌ๊ธฐ ๋ถ๋ถ!
x < 0 ||
y < 0 ||
x >= image.length ||
y >= image[x].length ||
image[x][y] === newColor ||
image[x][y] !== oldColor
)
return;
image[x][y] = newColor;
DFS(image, x + 1, y, oldColor, newColor);
DFS(image, x, y + 1, oldColor, newColor);
DFS(image, x - 1, y, oldColor, newColor);
DFS(image, x, y - 1, oldColor, newColor);
};
DFS๋ฅผ ์ด์ฉํ ๋ฌธ์ ๋ค. ๊ทธ ๋์ DFS, BFS์ ๋ํ ์ดํด๊ฐ ๋งค์ฐ ๋ถ์กฑํด์ ๊ด๋ จ๋ ๋ฌธ์ ๋ฅผ ๊ฑฐ์ ํ์ง ๋ชปํ์๋๋ฐ, ์ด๋ฒ์ ์ด ์์์ ๋ณด๊ณ ์กฐ๊ธ์ ๋ ์ดํด๋ฅผ ํ ๊ฒ ๊ฐ๋ค. DFS, BFS์ ๊ดํ ์ค๋ช ์ ํด๋น ์์์ ๋ณด๋๊ฒ ํจ์ฌ ์ดํด๊ฐ ๋น ๋ฅผ ๊ฒ์ด๋ค.
ํ์ด๋ ๋ค์๊ณผ ๊ฐ๋ค.
image[x][y]
๋ฅผ ํ๋์ node๋ผ๊ณ ์๊ฐํด๋ณด์.
image[x][y] = oldColor
๊ฐ ์๋ ๊ฒฝ์ฐ + 2์ฐจ์ ๋ฐฐ์ด image
์ ๋์ธ ๋ถ๋ถ(์ ์ฝ๋์ ์ฃผ์(!์ฌ๊ธฐ๋ถ๋ถ)์ ๋ณด์) + image[x][y]
๊ฐ newColor
์ธ ๊ฒฝ์ฐ(๋ฌธ์ ์์๋ ๋นจ๊ฐ์) ํ์์ ์ข
๋ฃํ๋ค๋ ์๋ฏธ์ด๋ค.
if
๋ฌธ์ ๊ฑธ๋ฆฌ๋ ๊ฒฝ์ฐ๋ฅผ ์ ์ธํ๊ณ ๋ 4๊ฐ์ DFS
ํจ์ ํธ์ถ์ ํตํด ์ฌ๊ท์ ์ผ๋ก ๋ค ๋ฐฉํฅ์ผ๋ก ๊ณ์ํด์ ํ์์ด ์ด๋ฃจ์ด์ง๋ค.
์์ , ์ง์ ์ ํ์ํฉ๋๋ค!
https://leetcode.com/problems/flood-fill/