LeetCode994. 腐烂的橘子( BFS )

力扣

LeetCode994. 腐烂的橘子( BFS )_第1张图片

                                

解题思路: 广度优先搜索

1. 先找到所有的腐烂橘子,入队 (queue),用第一批带出新一批腐烂的橘子
2. 每一批橘子都会在一分钟之内腐烂 , 所以此题可以转化为求 BFS 执行的大循环的次数
3. 这里的 step (次数)  的更新需要有一个标记,只有新的腐烂的橘子加入(queue不为空), step 才能自加
4. 最后 BFS 执行完之后,说明所有可以被腐烂的都完成了,再去遍历 grid, 如何还有 值为1 的,说明没有办法完全腐烂,返回 -1, 如果没有,则返回 step

                                                

class Solution 
{
public:   
    int dir[4][2] = {1 ,0 ,-1 ,0 ,0 ,1 ,0 ,-1} ;
    
    int orangesRotting(vector>& grid) 
    {
      //用pair存放位置 
      queue> q; 
      int row = grid.size(); 
      int col = grid[0].size(); 
      //已经腐烂的位置入队 
      for (int i = 0; i < row; ++i) 
      { 
          for (int j = 0; j < col; ++j) 
          { 
              if (grid[i][j] == 2) 
              q.push(make_pair(i, j)); 
          } 
       }

       int count = 0;
       while(!q.empty())
       {
           size_t sz = q.size();
          int  flag = 0;

           //用当前这一批已经腐烂的橘子带出下一批要腐烂的橘子 //故要遍历队列中的所有位置
           while(sz--)
           {
               int t_row = q.front().first;
               int t_col = q.front().second;
                q.pop();

               for(int i = 0 ; i < 4 ;++i)
               {
                   int new_row = t_row + dir[i][0];
                   int new_col = t_col + dir[i][1];
                    
                    if(new_row < 0 || new_row >= row || new_col < 0 || new_col >= col 
                    || grid[new_row][new_col] != 1)
                    continue; //如果位置越界或者是空格,或者已经是腐烂的位置,则跳过
                    
                    flag = 1;//标记有新的被腐烂
                    grid[new_row][new_col] = 2;
                    q.push(make_pair(new_row , new_col));
               }
               
           }

           if(flag)
           ++count;
       }

       for (int i = 0; i < row; ++i) 
       { 
          for (int j = 0; j < col; ++j) 
          { 
              if(grid[i][j] == 1)
              return -1;
          } 
       }

       return count;
    }

      
};

你可能感兴趣的:(力扣刷题,leetcode,队列,BFS)