LeetCode 994. 腐烂的橘子(多源bfs)

 

题目链接:https://leetcode-cn.com/problems/rotting-oranges/

       这道题刚开始看错题了,看到了图片就以为是就是从(0, 0)那个点开始,而且只有一个,然后敲完交了就wa了,然后才发现可能刚开始坏橘子有多个,而且还可能存在不连通的情况,所以就考虑多源bfs,刚开始将所有的坏橘子都扔进队列,然后bfs搜索就好了,不是很难,但是我的代码可能不太好读懂,我设置了一个嵌套pair的队列,也就是封装了三个参数,前两个是坐标,后一个是需要的天数( (.first.first, .first.second)这个表示坐标,.second表示需要的天数),然后将这个扔到队列中跑就好了,因为我在跑的过程中直接将新鲜的橘子变为坏橘子了,所以就没有用标记数组。

AC代码:

class Solution {
public:
    typedef pair<int,int> p;
    typedef pair<pair<int,int>, int> P;
    queue<pair<pair<int,int>,int> > q;
    int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
    int bfs(vector<vector<int> >& g){
        int n = g.size();
        int m = g[0].size();
        int cnt = 0;
        int ans = 0;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(g[i][j] == 2){
                    q.push(P(p(i, j), 0));
                }
                else if(g[i][j] == 1) cnt ++;
            }
        }
        while(!q.empty()){
            ans = max(ans, q.front().second);
            for(int i=0;i<4;i++){
                int x = q.front().first.first + dir[i][0];
                int y = q.front().first.second + dir[i][1];
                if(x >= 0 && y >= 0 && x < n && y < m && g[x][y] == 1){
                    g[x][y] = 2;
                    cnt --;
                    q.push(P(p(x, y), q.front().second + 1));
                }
                if(cnt == 0) break;
            }
            q.pop();
        }
        return cnt == 0 ? ans : -1;
    }
    int orangesRotting(vector<vector<int>>& g) {
        return bfs(g);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值