๐ก ๋ฌธ์
๐ฏ ํ์ด ๊ณผ์
BFS
๋ฅผ ์ด์ฉํด์ ๋๋ฌ ๊ฐ๋ฅํ ๋ชจ๋ ์ง์ ์ ํ์ธํ๋ ๋ฌธ์ ์
๋๋ค.
์ฌ๊ธฐ์ visit
์ด๋ผ๋ 2์ฐจ์ ๋ฐฐ์ด์ ์ ์งํ๋ฉฐ ์ค๋ณต ๋ฐฉ๋ฌธ์ ๊ฒ์ฌํจ๊ณผ ๋์์ ๋๋ฌ ๊ฐ๋ฅํ ์์น๋ฅผ ๊ธฐ๋กํฉ๋๋ค.
๐จโ๐ป ์ฝ๋
/**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} newColor
* @return {number[][]}
*/
var floodFill = function (image, sr, sc, newColor) {
const dr = [0, 0, 1, -1]
const dc = [1, -1, 0, 0]
const [ROW, COL] = [image.length, image[0].length]
function outOfRange(r, c) {
return r < 0 || r >= ROW || c < 0 || c >= COL
}
function bfs(sr, sc) {
const queue = []
const visit = Array.from(Array(ROW), () => Array(COL).fill(false))
queue.push([sr, sc])
visit[sr][sc] = true
while (queue.length > 0) {
const [hr, hc] = queue.shift()
for (let dir = 0; dir < 4; dir += 1) {
const [nr, nc] = [hr + dr[dir], hc + dc[dir]]
if (outOfRange(nr, nc) || visit[nr][nc]) {
continue
}
if (image[hr][hc] !== image[nr][nc]) {
continue
}
queue.push([nr, nc])
visit[nr][nc] = true
}
}
return visit
}
const reachable = bfs(sr, sc)
const answer = Array.from(Array(ROW), () => Array(COL).fill(0))
for (let row = 0; row < ROW; row += 1) {
for (let col = 0; col < COL; col += 1) {
if (reachable[row][col]) {
answer[row][col] = newColor
} else {
answer[row][col] = image[row][col]
}
}
}
return answer
}
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 35 - Search Insert Position (Easy) (0) | 2023.02.20 |
---|---|
LeetCode 169 - Majority Element (Easy) (2) | 2023.02.05 |
LeetCode 229 - Majority Element II (Medium) (0) | 2022.02.22 |
LeetCode 300 - Longest Increasing Subsequence (Medium) (0) | 2021.06.14 |
LeetCode 36 - Valid Sudoku (Medium) (0) | 2021.04.13 |
๐ฌ ๋๊ธ