当前位置:网站首页>994. rotten oranges - non recursive method
994. rotten oranges - non recursive method
2022-06-23 06:48:00 【Mr Gao】
994. Rotten oranges
In the given m x n grid grid in , Each cell can have one of three values :
value 0 For empty cells ;
value 1 For fresh oranges ;
value 2 For rotten oranges .
Every minute , Rotten oranges Around 4 Adjacent in two directions All fresh oranges rot .
return The minimum number of minutes that must elapse until there are no fresh oranges in the cell . If not , return -1 .
Example 1:
Input :grid = [[2,1,1],[1,1,0],[0,1,1]]
Output :4
Example 2:
Input :grid = [[2,1,1],[0,1,1],[1,0,1]]
Output :-1
explain : Orange in the lower left corner ( The first 2 That's ok , The first 0 Column ) Never rot , Because decay happens only in 4 Positive upward .
Example 3:
Input :grid = [[0,2]]
Output :0
explain : because 0 There are no fresh oranges by minute , So the answer is 0 .
The solution code is as follows :
int orangesRotting(int** grid, int gridSize, int* gridColSize){
int n=gridSize;
int m=gridColSize[0];
int fresh_man[m*n][2];
int num=0;
int i,j;
int size=0;
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(grid[i][j]==1){
fresh_man[size][0]=i;
fresh_man[size][1]=j;
size++;
}
}
}
int drection[4][2]={
{
0,1},{
1,0},{
0,-1},{
-1,0}};
int epo=0;
while(size!=0){
int num_sub=0;
for(i=0;i<size;i++){
int x=fresh_man[i][0];
int y=fresh_man[i][1];
for(j=0;j<4;j++){
int newx=x+drection[j][0];
int newy=y+drection[j][1];
if(newx>=0&&newx<n&&newy>=0&&newy<m){
if(grid[newx][newy]==2){
size--;
int tx=fresh_man[i][0];
int ty=fresh_man[i][1];
num_sub++;
fresh_man[i][0]=fresh_man[size][0];
fresh_man[i][1]=fresh_man[size][1];
fresh_man[size][0]=tx;
fresh_man[size][1]=ty;
i--;
break;
}
}
}
}
for(i=0;i<num_sub;i++){
grid[fresh_man[size+i][0]][fresh_man[size+i][1]]=2;
}
// printf("size %d numsub %d ",size,num_sub);
epo++;
if(num_sub==0){
break;
}
}
if(size!=0)return -1;
return epo;
}
边栏推荐
猜你喜欢

xml schem 记录

js创建数组(元素都是对象)

How to realize video call and live interaction in a small program when live broadcasting is so popular?

Usage Summary of item views and item widgets controls in QT

【系统】右键桌面图标,转圈后,资源管理器就崩溃,桌面就重新刷新

把CSMA/CD、Token Bus、Token Ring说清楚

Chrome删除重复书签

haas506 2.0开发教程-hota(仅支持2.2以上版本)

Easy EDA #学习笔记09# | ESP32-WROOM-32E模组ESP32-DevKitC-V4开发板 一键下载电路

Qt使用多线程编译项目的方法
随机推荐
core.js是什么---kalrry
光谱共焦的测量原理及厚度测量模式
20220621 Three Conjugates of Dual Quaternions
Laravel log channel grouping configuration
2022-01-12: give a positive array arr, length N, subscript 0~n-1, a
解决挖矿病毒 sshd2(redis未设密码、清除crontab定时任务)
C language stepping on the pit: document coding error, resulting in Base64 Chinese coding error
快速认识 WebAssembly
Linux安装mysql8.0.25
Leetcode notes: Weekly contest 298
haas506 2.0开发教程-hota(仅支持2.2以上版本)
xml schem 记录
如何迁移virtualbox 的虚拟机到hype-v
DQL、DML、DDL、DCL的概念与区别
js中if逻辑过多,常见优化
【Qt】基础学习笔记
将TensorFlow1.x改写为pytorch
Termux
Qt 中 QVariant 使用总结
idea安装 CloudToolkit 插件