leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

994. 腐烂的橘子

Open fireairforce opened this issue 5 years ago • 0 comments

这题是一个bfs比较典型的题目: 因为它要一圈一圈的找出去.

/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function(grid) {
    let count = 0;
    let list = [];
    for(let i = 0;i<grid.length;i++) {
        for(let j= 0;j<grid[0].length;j++) {
            if(grid[i][j] === 2) {
                list.push([i,j]);
            }
        }
    }
    // console.log(list)
    let res = 0;
    let dx = [1,-1,0,0];
    let dy = [0,0,1,-1];
    while(list.length) {
        let newList = [];
        for(let item of list) {
            let x0 = item[0];
            let y0 = item[1];
            for(let k = 0;k<4;k++) {
                let x = x0 + dx[k];
                let y = y0 + dy[k];
                if(0<=x && x< grid.length && 0<=y&&y<grid[0].length && grid[x][y] === 1) {
                    grid[x][y] = 2;
                    newList.push([x,y]);
                }
            }
        }
        if(newList.length === 0) {
            break;
        }
        list = newList
        res ++;
    }
    // 如果还有新鲜的
    for(let i = 0;i<grid.length;i++) {
        for(let j = 0;j<grid[0].length;j++) {
            if(grid[i][j] === 1){
                return -1;
            }
        }
    }
    return res;
};

fireairforce avatar Mar 04 '20 02:03 fireairforce