其他分享
首页 > 其他分享> > 994.腐烂的橘子

994.腐烂的橘子

作者:互联网

原题链接

题解

用BFS直接套就行

代码如下

class Solution {
public:
    int st[11][11];
    int orangesRotting(vector<vector<int>>& grid) {
        int lenx = grid.size();
        if(lenx == 0) return -1;
        int leny = grid[0].size();
        int sum = 0;
        int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0 ,0};
        queue<pair<int, int>> q;
        for(int i = 0; i < 11; ++i) memset(st[i], -1, sizeof st[i]);
        for(int i = 0; i < lenx; ++i){
            for(int j = 0; j < leny; ++j){
                if(grid[i][j] == 2) q.push({i, j}), st[i][j] = 0;
                else if(grid[i][j] == 1) sum ++;
            }
        }

        int res = 0;
        while(q.size()){
            auto t = q.front(); q.pop();
            if(st[t.first][t.second] != res) res ++; 
            for(int i = 0; i < 4; ++i){
                int x = t.first + dx[i];
                int y = t.second + dy[i];
                if(x >= 0 && x < lenx && y >= 0 && y < leny && st[x][y] == -1 && grid[x][y] == 1){
                    sum --;
                    q.push({x, y}), st[x][y] = st[t.first][t.second] + 1;
                }
            }
        }

        return sum == 0? res : -1;
    }
};

标签:994,int,sum,st,腐烂,++,grid,&&,橘子
来源: https://www.cnblogs.com/Lngstart/p/13339624.html