-
Notifications
You must be signed in to change notification settings - Fork 5
/
994. Rotting Oranges.java
58 lines (58 loc) · 1.76 KB
/
994. Rotting Oranges.java
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
class Solution {
public int orangesRotting(int[][] grid) {
int timeElapsed = 0;
int R = grid.length;
int C = grid[0].length;
// faster access for fresh / rotten
Set<String> freshOranges = new HashSet<String>();
Set<String> rottenOranges = new HashSet<String>();
for (int row = 0; row < R; row++) {
for (int col = 0; col < C; col++) {
int o = grid[row][col];
String key = generateKey(row, col);
if (o == 1)
freshOranges.add(key);
else if (o == 2)
rottenOranges.add(key);
}
}
int[] dx = new int[] { 1, -1, 0, 0 };
int[] dy = new int[] { 0, 0, -1, 1 };
// joto khon fresh orange ache
while (freshOranges.isEmpty() == false) {
Set<String> infected = new HashSet<String>();
for (String s : rottenOranges) {
int row = s.charAt(0) - '0';
int col = s.charAt(2) - '0';
for (int k = 0; k < 4; k++) {
int nrow = row + dx[k];
int ncol = col + dy[k];
String key = generateKey(nrow, ncol);
if (freshOranges.contains(key) == true) {
freshOranges.remove(key);
infected.add(key);
}
}
}
if (infected.size() == 0)
return -1;
rottenOranges.addAll(infected);
timeElapsed++;
}
return timeElapsed;
}
private String generateKey(int row, int col) {
// TODO Auto-generated method stub
return "" + row + "#" + col;
}
}