-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRottenOranges.java
More file actions
80 lines (75 loc) · 2.6 KB
/
RottenOranges.java
File metadata and controls
80 lines (75 loc) · 2.6 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class RottenOranges {
Queue<int[]> queue;
int count_fresh = 0;
int grid[][];
int rows;
int cols;
public RottenOranges(int[][] grid) {
queue = new LinkedList<>();
this.grid = grid;
rows = grid.length;
cols = grid[0].length;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, m;
n = s.nextInt();
m = s.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
grid[i][j] = s.nextInt();
}
}
RottenOranges obj = new RottenOranges(grid);
obj.countFresh();
System.out.println(obj.rot());
}
private void countFresh() {
//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});
}
else if(grid[i][j] == 1) {
count_fresh++;
}
}
}
}
private int rot() {
//if count of fresh oranges is zero --> return 0
if(count_fresh == 0) return 0;
int count = 0;
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
//bfs starting from initially rotten oranges
while(!queue.isEmpty()) {
++count;
int size = queue.size();
for(int i = 0 ; i < size ; i++) {
int[] point = queue.poll();
for(int dir[] : dirs) {
int x = point[0] + dir[0];
int y = point[1] + dir[1];
//if x or y is out of bound
//or the orange at (x , y) is already rotten
//or the cell at (x , y) is empty
//we do nothing
if(x < 0 || y < 0 || x >= rows || y >= cols || grid[x][y] == 0 || grid[x][y] == 2) continue;
//mark the orange at (x , y) as rotten
grid[x][y] = 2;
//put the new rotten orange at (x , y) in queue
queue.offer(new int[]{x , y});
//decrease the count of fresh oranges by 1
count_fresh--;
}
}
}
return count_fresh == 0 ? count-1 : -1;
}
}