
- 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;
- }
- };
-
相关阅读:
Nginx网站服务(nginx监控模块vts、nginx配置文件介绍、nginx多种访问配置)
17-ROS tf包介绍
学单片机怎么在3-5个月内找到工作?
Sanitizers 系列之 address sanitizer 原理篇
R语言绘图—制作你的专属“足迹“图
【校招VIP】前端校招考点之UDP
Cortex-A9 架构
Ubuntu18.04安装onnxruntime(c++版)与CUDA运行Demo
摩根大通研究论文:大型语言模型+自动规划器用来作有保障的旅行规划
一文读懂spring.factories作用
-
原文地址:https://blog.csdn.net/qq_52313711/article/details/134051151