-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotting_oranges.go
67 lines (59 loc) · 1.26 KB
/
rotting_oranges.go
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
package grind75
import (
"github.com/lovung/ds/queue"
)
// Link: https://leetcode.com/problems/rotting-oranges/
type pointWithDis struct{ i, j, dis int }
type point struct{ i, j int }
func orangesRotting(grid [][]int) int {
cacheDistance := make(map[point]int)
q := queue.NewSimpleQueue[pointWithDis]()
for i := range grid {
for j := range grid[i] {
if grid[i][j] == 2 {
q.EnQueue(pointWithDis{i, j, 0})
} else if grid[i][j] == 1 {
cacheDistance[point{i, j}] = -1
}
}
}
if q.Len() == 0 && len(cacheDistance) > 0 {
return -1
}
for q.Len() > 0 {
orange, _ := q.DeQueue()
floody(grid, cacheDistance, q, orange.i, orange.j, orange.dis)
}
maxDis := 0
for _, v := range cacheDistance {
if v == -1 {
return -1
}
maxDis = max(maxDis, v)
}
return maxDis
}
func floody(
grid [][]int, cache map[point]int,
q queue.Queue[pointWithDis],
i, j int, dis int,
) {
for _, d := range dir {
_i := i + d[0]
_j := j + d[1]
if !inBound(grid, _i, _j) {
continue
}
if grid[_i][_j] == 2 {
continue
}
if grid[_i][_j] == 1 {
if cache[point{_i, _j}] == -1 {
cache[point{_i, _j}] = dis + 1
q.EnQueue(pointWithDis{_i, _j, cache[point{_i, _j}]})
} else {
cache[point{_i, _j}] = min(cache[point{_i, _j}], dis+1)
}
}
}
}