-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
66 lines (63 loc) · 2.05 KB
/
Solution.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
59
60
61
62
63
64
65
66
class Solution {
private int[] dist = new int[3600];
private List<List<Integer>> forest;
private int m;
private int n;
public int cutOffTree(List<List<Integer>> forest) {
this.forest = forest;
m = forest.size();
n = forest.get(0).size();
List<int[]> trees = new ArrayList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (forest.get(i).get(j) > 1) {
trees.add(new int[] {forest.get(i).get(j), i * n + j});
}
}
}
trees.sort(Comparator.comparingInt(a -> a[0]));
int ans = 0;
int start = 0;
for (int[] tree : trees) {
int end = tree[1];
int t = bfs(start, end);
if (t == -1) {
return -1;
}
ans += t;
start = end;
}
return ans;
}
private int bfs(int start, int end) {
PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
q.offer(new int[] {f(start, end), start});
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
int[] dirs = {-1, 0, 1, 0, -1};
while (!q.isEmpty()) {
int state = q.poll()[1];
if (state == end) {
return dist[state];
}
for (int k = 0; k < 4; ++k) {
int x = state / n + dirs[k];
int y = state % n + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && forest.get(x).get(y) > 0) {
if (dist[x * n + y] > dist[state] + 1) {
dist[x * n + y] = dist[state] + 1;
q.offer(new int[] {dist[x * n + y] + f(x * n + y, end), x * n + y});
}
}
}
}
return -1;
}
private int f(int start, int end) {
int a = start / n;
int b = start % n;
int c = end / n;
int d = end % n;
return Math.abs(a - c) + Math.abs(b - d);
}
}