-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
63 lines (55 loc) · 1.72 KB
/
Solution.cs
File metadata and controls
63 lines (55 loc) · 1.72 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
public class Solution
{
public int OrangesRotting(int[][] grid)
{
int maxR = grid.Length - 1;
int maxC = grid[0].Length - 1;
Queue<(int r, int c)> rottenQueue = [];
int freshCount = 0;
for (int i = 0; i <= maxR; i++)
{
for (int j = 0; j <= maxC; j++)
{
if (grid[i][j] == 1) freshCount++;
if (grid[i][j] == 2) rottenQueue.Enqueue((i, j));
}
}
if (freshCount == 0) return 0;
int minuteNumber = -1;
while (rottenQueue.Count > 0)
{
minuteNumber++;
int length = rottenQueue.Count;
for (int i = 0; i < length; i++)
{
var (r, c) = rottenQueue.Dequeue();
if (r - 1 >= 0 && grid[r - 1][c] == 1)
{
grid[r - 1][c] = 2;
freshCount--;
rottenQueue.Enqueue((r - 1, c));
}
if (r + 1 <= maxR && grid[r + 1][c] == 1)
{
grid[r + 1][c] = 2;
freshCount--;
rottenQueue.Enqueue((r + 1, c));
}
if (c + 1 <= maxC && grid[r][c + 1] == 1)
{
grid[r][c + 1] = 2;
freshCount--;
rottenQueue.Enqueue((r, c + 1));
}
if (c - 1 >= 0 && grid[r][c - 1] == 1)
{
grid[r][c - 1] = 2;
freshCount--;
rottenQueue.Enqueue((r, c - 1));
}
}
}
if (freshCount > 0) return -1;
return minuteNumber;
}
}