๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 733 - Flood Fill (Easy)

by HandHand 2022. 3. 7.

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 733๋ฒˆ

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

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

๐Ÿ’ฌ ๋Œ“๊ธ€