forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrottenOrangesJava
48 lines (44 loc) · 1.59 KB
/
rottenOrangesJava
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
class Solution {
public int orangesRotting(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int rows = grid.length;
int cols = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int count_fresh = 0;
//Put the position of all rotten oranges in queue
//count the number of fresh oranges
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < cols ; j++) {
if(grid[i][j] == 2) {
queue.offer(new int[]{i , j});
}
if(grid[i][j] != 0) {
count_fresh++;
}
}
}
if(count_fresh == 0) return 0;
int countMin = 0, cnt = 0;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
//bfs starting from initially rotten oranges
while(!queue.isEmpty()) {
int size = queue.size();
cnt += size;
for(int i = 0 ; i < size ; i++) {
int[] point = queue.poll();
for(int j = 0;j<4;j++) {
int x = point[0] + dx[j];
int y = point[1] + dy[j];
if(x < 0 || y < 0 || x >= rows || y >= cols || grid[x][y] == 0 || grid[x][y] == 2) continue;
grid[x][y] = 2;
queue.offer(new int[]{x , y});
}
}
if(queue.size() != 0) {
countMin++;
}
}
return count_fresh == cnt ? countMin : -1;
}
}