forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0994-rotting-oranges.cs
51 lines (44 loc) · 1.54 KB
/
0994-rotting-oranges.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
publicclassSolution{
publicintOrangesRotting(int[][]grid)
{
if(grid==null||grid[0].Length==0)
return0;
intr=grid.Length,c=grid[0].Length,fresh=0,time=0;
Queue<(int,int)>q=newQueue<(int,int)>();
for(inti=0;i<r;i++)
{
for(intj=0;j<c;j++)
{
if(grid[i][j]==1)
fresh++;
elseif(grid[i][j]==2)
{
q.Enqueue((i,j));
};
}
}
if(fresh==0)
return0;
int[,]dir=newint[,]{{-1,0},{1,0},{0,-1},{0,1}};
while(q.Any())
{
time++;
intsize=q.Count;
for(inti=0;i<size;i++)
{
varcurr=q.Dequeue();
for(intj=0;j<4;j++)
{
introw=curr.Item1+dir[j,0];
intcol=curr.Item2+dir[j,1];
if(row>=0&&row<r&&col>=0&&col<c&&grid[row][col]==1)
{
grid[row][col]=2;
q.Enqueue((row,col));
fresh--;
}
}
}
}
returnfresh==0?time-1:-1;
}}