Skip to content

Commit 184b172

Browse files
committed
general BFS to finnd minimum time
1 parent 89157ae commit 184b172

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

BFS/rottenOranges.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Cell {
2+
int x;
3+
int y;
4+
public Cell(int x, int y) {
5+
this.x = x;
6+
this.y = y;
7+
}
8+
}
9+
class Solution {
10+
int[][] dir = {{-1,0}, {1,0}, {0,-1}, {0,1}};
11+
public int orangesRotting(int[][] grid) {
12+
Queue<Cell> q = new LinkedList<>();
13+
int count_fresh = 0;
14+
for (int i=0; i<grid.length; i++) {
15+
for (int j=0; j<grid[0].length; j++) {
16+
if (grid[i][j] == 2) {
17+
Cell rottenCell = new Cell(i, j);
18+
q.add(rottenCell);
19+
} else if (grid[i][j] == 1) {
20+
count_fresh++;
21+
}
22+
}
23+
}
24+
25+
if (count_fresh == 0) return 0;
26+
int time = 0;
27+
while(!q.isEmpty()) {
28+
time++;
29+
int size = q.size();
30+
for (int times = 0; times < size; times++) {
31+
Cell curCell = q.poll();
32+
for (int[] d: dir) {
33+
int new_r = d[0] + curCell.x;
34+
int new_c = d[1] + curCell.y;
35+
if (new_r >=0 && new_c >= 0 && new_r < grid.length && new_c < grid[0].length && (grid[new_r][new_c] == 1)) {
36+
Cell newCell = new Cell(new_r, new_c);
37+
grid[new_r][new_c] = 2;
38+
q.add(newCell);
39+
count_fresh--;
40+
}
41+
}
42+
}
43+
}
44+
if (count_fresh != 0) return -1;
45+
return time == 0 ? -1: time-1;
46+
}
47+
}

0 commit comments

Comments
 (0)