xinyu04

导航

LeetCode 994 Rotting Oranges BFS

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return \(-1\).

Solution

依旧还是 \(BFS\), 不过这次需要将三元组 \((i,j,cur\_t)\) 压入队列,每次更新答案时:

\[ans=\max(ans,cur\_t) \]

当最后的图还有 fresh orange 时,说明 \(impossible\)

点击查看代码
class Solution {
private:
    int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};
    
    bool check(int x,int y,int r,int c){
        if(x<0||y<0||x>=r||y>=c)return false;
        return true;
    }
    int fg = 1;
    int vis[11][11];
    int ans = -1;
    bool ck_vis = 1;
    queue<vector<int>> q;
    
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int r = grid.size(), c = grid[0].size();
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(grid[i][j]==1)fg=0;
                else if(grid[i][j]==2)q.push({i,j,0});
            }
        }
        if(fg) return 0;
        while(!q.empty()){
            auto f = q.front();q.pop();
            int x = f[0], y = f[1], cur_time = f[2];
            ans = max(ans, cur_time);
            if(vis[x][y])continue;
            vis[x][y] = 1;
            
            for(int i=0;i<4;i++){
                int nx = x+dir[i][0], ny = y+dir[i][1];
                if(check(nx,ny,r,c)){
                    if(grid[nx][ny]==0)continue;
                    else if(vis[nx][ny])continue;
                    if(!vis[nx][ny] && grid[nx][ny]==1){
                        grid[nx][ny]=2;
                        q.push({nx,ny,cur_time+1});
                    }
                }
                
            }
        }
        
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                if(grid[i][j]==1)return -1;
        
        return ans;
        
    }
};

posted on 2022-07-23 16:31  Blackzxy  阅读(13)  评论(0编辑  收藏  举报