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
|
func cutOffTree(forest [][]int) int {
m, n := len(forest), len(forest[0])
type tree struct{ h, x, y int }
var trees []tree
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if forest[i][j] > 1 {
trees = append(trees, tree{forest[i][j], i, j})
}
}
}
sort.Slice(trees, func(i, j int) bool { return trees[i].h < trees[j].h })
dirs := [][2]int{{0,1},{1,0},{0,-1},{-1,0}}
bfs := func(sx, sy, tx, ty int) int {
if sx == tx && sy == ty {
return 0
}
vis := make([][]bool, m)
for i := range vis {
vis[i] = make([]bool, n)
}
q := [][2]int{{sx, sy}}
vis[sx][sy] = true
d := 0
for len(q) > 0 {
d++
sz := len(q)
for i := 0; i < sz; i++ {
x, y := q[0][0], q[0][1]
q = q[1:]
for _, dir := range dirs {
nx, ny := x+dir[0], y+dir[1]
if nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && forest[nx][ny] != 0 {
if nx == tx && ny == ty {
return d
}
vis[nx][ny] = true
q = append(q, [2]int{nx, ny})
}
}
}
}
return -1
}
ans, cx, cy := 0, 0, 0
for _, t := range trees {
d := bfs(cx, cy, t.x, t.y)
if d == -1 {
return -1
}
ans += d
cx, cy = t.x, t.y
}
return ans
}
|