当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
什么是客户体验自动化?
How to maintain secure encryption of email communication with FDA?
剑指 Offer 42. 连续子数组的最大和
Synchronous switching power supply reduces EMI layout dv/dt di/dt
leetcode - 572. 另一棵树的子树
【shell】Tree命令
Kubesphere offline deployment without network environment
Explain csma/cd, token bus and token ring clearly
XXL-SSO 实现SSO单点登录
JS to create an array (all elements are objects)
2022-01-12: give a positive array arr, length N, subscript 0~n-1, a
解析创客教育中的造物原理
Easy EDA #学习笔记09# | ESP32-WROOM-32E模组ESP32-DevKitC-V4开发板 一键下载电路
Measurement principle and thickness measurement mode of spectral confocal
利用fuser查看文件使用情况
开源OAuth2框架 实现SSO单点登录
Termux
中台库存中的实仓与虚仓的业务逻辑设计
云盒子联合深信服,为南京一中打造智慧双模教学资源分享平台
利用adb 调试设备串口信息的一个小方法









