
- class Solution {
- public:
- int orangesRotting(vector
int >>& grid) { - /*统计grid二维数组中有多少新鲜橘子和多少烂橘子,将所有的烂橘子存入一个三元队列中
- 其中,队列前两个参数表示烂橘子坐标,第三个参数代表是第几代烂橘子
- 同时,统计新鲜橘子数量*/
- int m = grid.size();
- int n = grid[0].size();
- int fresh=0;
- queue
int,int,int>> q; - for(int i=0;i
- for(int j=0;j
- if(grid[i][j]==1){
- fresh++;//记录新鲜橘子数量
- }else if(grid[i][j]==2){
- q.emplace(i,j,0);//将烂橘子存入队列,第三个参数0表示都是最初的烂橘子
- }
- }
- }
-
- vector<int> dx ={1,0,-1,0};
- vector<int> dy ={0,1,0,-1};
- int time =0;//记录队列最后一个烂橘子是第几代
- while(!q.empty()){
- auto [cx,cy,d]=q.front();
- time=d;
- q.pop();
- for(int i=0;i<4;++i){
- int nx=cx+dx[i];
- int ny=cy+dy[i];
- //检查烂橘子四个方向上的是否在二维数组内部且是否是新鲜橘子
- if(nx>=0 && nx
=0 && ny1){ - grid[nx][ny]=2;//将其变成烂橘子
- fresh--;//新鲜橘子减少
- q.emplace(nx,ny,d+1);//将烂橘子存入队列,并且标记其是第几代烂橘子
- }
- }
- }
- if(fresh>0){
- return -1;
- }else{
- return time;
- }
- }
- };
代码(二刷瞄了眼思路 2024年3月7日)
- class Solution {
- public:
- void BFS(vector
int >>& grid, int row, int column, queueint ,int>>& q) { - int nr = grid.size();
- int nc = grid[0].size();
-
- if (row - 1 >= 0 && grid[row - 1][column] == 1)
- { grid[row-1][column] = 2; q.push(make_pair(row - 1, column));}
- if (row + 1 < nr && grid[row + 1][column] == 1)
- { grid[row+1][column] = 2; q.push(make_pair(row + 1, column));}
- if (column - 1 >= 0 && grid[row][column - 1] == 1)
- { grid[row][column - 1] = 2; q.push(make_pair(row, column - 1));}
- if (column + 1 < nc && grid[row][column + 1] == 1)
- { grid[row][column + 1] = 2; q.push(make_pair(row, column + 1));}
- }
-
- int orangesRotting(vector
int >>& grid) { - int nr = grid.size();
- if (nr == 0) return 0;
- int nc = grid[0].size();
- queue
int,int>> q; - int orange = 0;
-
- for (int i = 0; i < nr; ++i) {
- for (int j = 0; j < nc; ++j) {
- if (grid[i][j] == 1 || grid[i][j] == 2) orange++;
- if (grid[i][j] == 2) {
- q.push(make_pair(i, j));
- }
- }
- }
-
- int time = 0;
- int toxic_orange = 0;
- while (!q.empty()) {
- int size = q.size();
- while (size--) {
- auto it = q.front();
- toxic_orange++;
- q.pop();
- BFS(grid, it.first, it.second, q);
- }
- time++;
- }
- if (time) time--;
- return orange == toxic_orange ? time : -1;
- }
- };
-
相关阅读:
[巅峰极客 2022]smallcontainer
如何使用 Python 在终端中创建令人惊叹的图形
MyBatis 的在使用上的注意事项及其辨析
前端入门到入土?
springboot 实现权限管理(一)
RS笔记:深度推荐模型之SIM(基于搜索的超长行为序列上的用户长期兴趣建模)[CIKM 2020, 阿里妈妈广告团队]
关于安卓自定义弹幕控件的实现(recyclerview)(一)
JavaSE - 调用和重写Object类中的toString方法、equals方法以及理解Arrays类中的toString方法
【App自动化测试】(七)移动端自动化中常见控件交互方法
稳压二极管稳压电路如何设计
-
原文地址:https://blog.csdn.net/qq_52313711/article/details/134051151