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;
    }
};
posted @ 2020-07-19 14:30  Lngstart  阅读(129)  评论(0编辑  收藏  举报