leetcode-华为专题-994. 腐烂的橘子

 

 

struct point{
    int x;
    int y;
};
class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int freshfruit = 0;
        queue<point> q;
        for(int i = 0; i < grid.size(); i++){
            for(int j = 0; j < grid[0].size(); j++){
                if(grid[i][j]==1){
                    freshfruit++;  // 统计新鲜水果个数
                }else if(grid[i][j] == 2){
                    q.push(point{i,j});  // 将原始腐烂水果坐标加入队列
                }
            }
        }
        // bfs 广度优先遍历
        int layer = 0; // 层次
        // 1.一轮遍历队列中所有腐烂的水果;
        // 2.判断腐烂水果的四个方向,将他们变腐烂
        // 3.下一轮待遍历的腐烂水果进队
        // 直到某一轮过后无新鲜水果或队列为空(无腐烂水果进队)=》循环结束
        while(freshfruit>0&&!q.empty()){
            layer++;  // 
            int n = q.size();
            // 下面对每一层进行处理
            for(int i = 0; i < n; i++){
                point tmp = q.front();
                q.pop();
                int m = tmp.x;
                int n = tmp.y;
                //
                if((m-1)>=0&&grid[m-1][n]==1){
                    grid[m-1][n] = 2;  // 将新鲜水果进行腐烂
                    freshfruit--;  // 新鲜水果个数减1
                    q.push(point{m-1,n});  // 加入新节点
                }
                //
                if((m+1)<grid.size()&&grid[m+1][n]==1){
                    grid[m+1][n] = 2;
                    freshfruit--;
                    q.push(point{m+1,n});
                }
                //
                if((n-1)>=0&&grid[m][n-1]==1){
                    grid[m][n-1] = 2;
                    freshfruit--;
                    q.push(point{m,n-1});
                }
                //
                if((n+1)<grid[0].size()&&grid[m][n+1]==1){
                    grid[m][n+1] = 2;
                    freshfruit--;
                    q.push(point{m,n+1});
                }
            }

        }
        if(freshfruit==0)
            return layer;
        else
            return -1;
    }
};

 

posted @ 2021-10-08 16:43  三一一一317  阅读(64)  评论(0)    收藏  举报