【leetcode】994. 腐烂的橘子

63 阅读1分钟

image.png

对于这种波及类型的题目,无非两种方案
1.DFS
2.BFS
这这一题里面,只能用BFS来解决,因为涉及到层次的问题,所以BFS是专用来解决这类题目的

var orangesRotting = function (grid) {
    let mins = 0
    let row = grid.length, col = grid[0].length
    let direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    let fresh = 0
    let queue = []
    var bfs = function () {
        while (queue.length && fresh) {
            let size = queue.length
            for (let i = 0; i < size; ++i) {
                // 当前这一轮橘子进行腐败
                let [x, y] = queue.shift()
                for (let [dx, dy] of direction) {
                    let fx = dx + x
                    let fy = dy + y
                    if (fx >= 0 && fx < row && fy >= 0 && fy < col && grid[fx][fy] === 1) {
                        // 新一轮入队
                        queue.push([fx, fy])
                        // 重新标记腐烂橘子
                        grid[fx][fy] = 2
                        // 减少新鲜橘子个数
                        fresh--
                    }
                }
            }
            // 结束其中一轮
            mins++
        }
    }
    for (let i = 0; i < row; ++i) {
        for (let j = 0; j < col; ++j) {
            if (grid[i][j] === 2) {
                // 因为有多个点位可能出现腐烂的橘子
                queue.push([i, j])
            } else if (grid[i][j] === 1) {
                // 用来判断橘子是否都可以腐烂
                fresh++
            }
        }
    }
    bfs()
    return fresh ? -1 : mins
};