-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path994. Rotting Oranges
More file actions
54 lines (51 loc) · 1.72 KB
/
Copy path994. Rotting Oranges
File metadata and controls
54 lines (51 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
public class Solution {
public int OrangesRotting(int[][] grid) {
int minutes=0;
int fresh=0;
var q = new Queue<(int,int)>();
for(int i =0; i< grid.Length; i++)
{
for(int j =0; j< grid[0].Length; j++)
{
if(grid[i][j] ==2)
q.Enqueue((i,j));
else if(grid[i][j] ==1)
fresh++;
}
}
int[][] directions = new int[][]{
new int[] {1,0},
new int[] {-1,0},
new int[] {0,1},
new int[] {0,-1}
};
while (q.Count > 0 && fresh >0)
{
int len = q.Count;
// I only loop one stop from each of initial source nodes
// propagate or calulate the effect that I need
// and then loop again on the second layer I added and so on.
// So It's multi source BFS in the sense that I do it concurrently
//and terminate and concurrently and terminate
// until all is visited or effect is propagated
for(int i =0; i< len; i++)
{
var cell = q.Dequeue();
foreach(var dir in directions)
{
var x = cell.Item1+ dir[0];
var y = cell.Item2 + dir[1];
if(x >= 0 && x < grid.Length && y >= 0 && y < grid[0].Length
&& grid[x][y] ==1 )
{
grid[x][y] = 2;
q.Enqueue((x,y));
fresh--;
}
}
}
minutes++;
}
return fresh ==0 ? minutes : -1;
}
}