Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

994. 腐烂的橘子 #39

Open
fireairforce opened this issue Mar 4, 2020 · 0 comments
Open

994. 腐烂的橘子 #39

fireairforce opened this issue Mar 4, 2020 · 0 comments
Labels
easy This issue or pull request already exists 常规题目 Further information is requested

Comments

@fireairforce
Copy link
Owner

这题是一个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 fireairforce added easy This issue or pull request already exists 常规题目 Further information is requested labels Mar 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
easy This issue or pull request already exists 常规题目 Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant