π‘ λ¬Έμ
π― νμ΄ κ³Όμ
맀 λ¨μμκ°(minute) λ§λ€ μ©μ μ€λ μ§μ μΈμ ν 4λ°©ν₯μ μμΉν μ€λ μ§κ° ν¨κ» μ©λλ€κ³ ν λ
μ£Όμ΄μ§ grid
μμ λͺ¨λ μ€λ μ§κ° μ©κΈ°κΉμ§ 걸리λ μκ°μ ꡬνλ λ¬Έμ μ
λλ€.
μΌλ°μ μΈ BFS
νμμμ μ½κ°μ λ³νμ΄ νμν μ νμ
λλ€.
μ©μ μ€λ μ§λ₯Ό queue
μ λ£μ΄μ£Όκ³ queue
κ° λΉμ΄μ§λκΉμ§ λ°λ³΅ν΄μΌμ§
κ°κ°μ λ¨μ μκ°λ§λ€ νμ¬ queue
μ λ΄κ²¨μλ μ€λ μ§λ€μ λν΄ BFS
λ₯Ό ν μ μμ΅λλ€.
λ³΄ν΅ BFS
λ₯Ό ν λ μ€λ³΅ λ°©λ¬Έμ νΌνκΈ° μν΄ visit
κ°μ μλ£κ΅¬μ‘°λ₯Ό λ§λ€μ΄ μ΄μ©νλλ°,
μ¬κΈ°μλ μ€λ μ§κ° μ©μ μνμΌ λλ₯Ό μ΄λ―Έ λ°©λ¬Έν μμΉλ‘ νλ¨μ΄ κ°λ₯νλ―λ‘
λ°©λ¬Έμ¬λΆλ₯Ό μν λ³λμ μλ£κ΅¬μ‘°λ λ§λ€μ΄μ£Όμ§ μκ³ μνκ°μΌλ‘ νλ¨νλλ‘ ν μ μμ΅λλ€.
π¨π» μ½λ
/**
* @param {number[][]} grid
* @return {number}
*/
var orangesRotting = function(grid) {
const [ROW, COL] = [grid.length, grid[0].length]
const dr = [1, -1, 0, 0]
const dc = [0, 0, 1, -1]
const queue = []
function preparation() {
for (let row = 0; row < ROW; row += 1) {
for (let col = 0; col < COL; col += 1) {
const isRotten = grid[row][col] === 2
if (isRotten) {
queue.push([row, col])
}
}
}
}
function outOfRange(row, col) {
return row < 0 || row >= ROW || col < 0 || col >= COL
}
function rottening() {
let minute = -1
while (queue.length > 0) {
let iterate = queue.length
while (iterate > 0) {
const [hr, hc] = queue.shift()
for (let dir = 0; dir < 4; dir += 1) {
const [nr, nc] = [dr[dir] + hr, dc[dir] + hc]
if (outOfRange(nr, nc)) {
continue
}
const isEmpty = grid[nr][nc] === 0
const isRotten = grid[nr][nc] === 2
if (isEmpty || isRotten) {
continue
}
grid[nr][nc] = 2 // now, adjacent orange is rottening
queue.push([nr, nc])
}
iterate -= 1
}
minute += 1
}
return minute
}
preparation()
const minute = rottening()
for (let row = 0; row < ROW; row += 1) {
for (let col = 0; col < COL; col += 1) {
const isFresh = grid[row][col] === 1
if (isFresh) {
return -1
}
}
}
return Math.max(minute, 0)
};
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 15 - 3Sum (Medium) (0) | 2023.04.24 |
---|---|
LeetCode 13 - Roman to Integer (Easy) (0) | 2023.04.24 |
LeetCode 24 - Swap Nodes in Pairs (Medium) (0) | 2023.02.20 |
LeetCode 35 - Search Insert Position (Easy) (0) | 2023.02.20 |
LeetCode 169 - Majority Element (Easy) (2) | 2023.02.05 |
π¬ λκΈ