Leetcode 994. 腐烂的橘子 题解

题目链接:https://leetcode-cn.com/problems/rotting-oranges/
Leetcode 994. 腐烂的橘子 题解_第1张图片
Leetcode 994. 腐烂的橘子 题解_第2张图片
一分钟写完系列,可以直接把二维坐标一维化

代码如下:

class Solution {
public:
    bool inmap(int xx, int yy, int n, int m) {
        return xx >= 0 && xx < n && yy >= 0 && yy < m;
    }

    int orangesRotting(vector<vector<int>>& grid) {
        int res = 0;
        int n = grid.size();
        if(n == 0) {
            return 0;
        }
        int m = grid[0].size();
        queue<int> q;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 2) {
                    q.push(i * m + j);
                }
            }
        }
        int dx[4] = {-1, 0, 1, 0};
        int dy[4] = {0, -1, 0, 1};
        while(!q.empty()) {
            int len = q.size();
            while(len--) {
                int now = q.front();
                q.pop();
                int x = now / m;
                int y = now % m;
                for(int i = 0; i < 4; i++) {
                    int xx = x + dx[i], yy = y + dy[i];
                    if(inmap(xx, yy, n, m) && grid[xx][yy] == 1) {
                        grid[xx][yy] = 0;
                        q.push(xx * m + yy);
                        // printf("xx = %d, yy = %d\n", xx, yy);
                    }
                }
            }
            res++;
        }
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 1) {
                    return -1;
                }
            }
        }
        return max(0, res - 1);
    }
};

你可能感兴趣的:(DFS_BFS,Leetcode)