Skip to content

Commit 1881b54

Browse files
Create 0994-rotting-oranges.go
Accepted submission: _https://leetcode.com/submissions/detail/870871137/_
1 parent 4701955 commit 1881b54

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Diff for: go/0994-rotting-oranges.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const ROW = 0
2+
const COL = 1
3+
func orangesRotting(grid [][]int) int {
4+
q := make([][]int, 0)
5+
fresh := 0
6+
time := 0
7+
8+
for r := 0; r < len(grid); r++ {
9+
for c := 0; c < len(grid[0]); c++ {
10+
if grid[r][c] == 1 {
11+
fresh += 1
12+
}
13+
if grid[r][c] == 2 {
14+
q = append(q, []int{r, c})
15+
}
16+
}
17+
}
18+
19+
directions := [4][2]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
20+
for fresh > 0 && len(q) != 0 {
21+
length := len(q)
22+
for i := 0; i < length; i++ {
23+
cell := q[0]
24+
q = q[1:]
25+
26+
for _, d := range directions {
27+
row, col := cell[ROW] + d[ROW], cell[COL] + d[COL]
28+
29+
// if in bounds and notrotten, make rotten
30+
// and add to q
31+
if(
32+
row >= 0 && row < len(grid) &&
33+
col >= 0 && col < len(grid[0]) &&
34+
grid[row][col] == 1) {
35+
grid[row][col] = 2
36+
q = append(q, []int{row, col})
37+
fresh -= 1
38+
}
39+
}
40+
}
41+
time += 1
42+
}
43+
44+
if fresh == 0 {
45+
return time;
46+
}
47+
return -1
48+
}

0 commit comments

Comments
 (0)