994. 腐烂的橘子(宽搜+队列)

题目描述

leetcode - 994:https://leetcode-cn.com/problems/container-with-most-water/

题目描述 题目描述

解题关键

  • 宽搜

碎碎念

这题除了用 宽搜 以外,还用了 结构体 来存数据,因为需要记录搜索中的层数。宽搜得到的树的 高度 其实就是答案。
用了 队列 来进行搜索。

代码

  • 时间复杂度O(MN) M是图的长,N是图的宽
  • 空间复杂度O(MN)
struct Orange {
    int x=-1;     // 该点x轴的位置 
    int y=-1;     // 该点y轴的位置 
    int dep=-1;   // 该点所处深度
};
int orangesRotting(vector<vector<int>>& grid) {
    int row= grid.size();        //行
    int col = grid[0].size();    //列
    int xdir[4] = {0,1,0,-1};
    int ydir[4] = {1,0,-1,0};
    queue<Orange> Q; //(x,y)     // 结构体队列
    int time = 0;
    int count=0;      // 记录新鲜果子的熟练,用来判断所有新鲜果子是否都被搜索到了
    for(int i=0;i<row;i++){
        for(int j=0;j<col;j++){
            if(grid[i][j]==2){      // 坏果子存进队列中
                Orange one;
                one.x = i; one.y = j; one.dep = time;
                Q.push(one);
            }
            if(grid[i][j]==1)      // 新鲜果子统计
                count++;
        }
    }
    while(!Q.empty()){
        Orange tmp = Q.front();      // 获取队列的第一个点
        Q.pop();                     // 删除队列的第一个点
        for(int i=0;i<4;i++){        // 四个方向搜索
            int tx = tmp.x + xdir[i];   // row
            int ty = tmp.y + ydir[i];   // col
            int tdep = tmp.dep+1;
            if( tx>=0 && tx<row && ty>=0 && ty<col && grid[tx][ty]==1 ){  // 图内的点,并且点上有新鲜果子
                // 把新鲜果子放进队列,并且把层数+1,还要把新鲜果子变成坏果子2
                Orange fresh;
                fresh.x = tx;  fresh.y = ty;  fresh.dep = tdep;
                Q.push(fresh);
                grid[tx][ty] = 2;
                time = time>tdep?time:tdep;
                count--;
            }
        }
    }
    if(count)  return -1;
    return time;
}
posted @ 2020-06-02 17:41  _Sleeping  阅读(167)  评论(0)    收藏  举报