-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathWithMinimumEffort.java
More file actions
74 lines (64 loc) · 2.28 KB
/
PathWithMinimumEffort.java
File metadata and controls
74 lines (64 loc) · 2.28 KB
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
68
69
70
71
72
73
74
package leetcode;
import java.util.Queue;
import java.util.concurrent.LinkedTransferQueue;
/**
* PathWithMinimumEffort
* https://leetcode-cn.com/problems/path-with-minimum-effort
* 1631. 最小体力消耗路径
* https://leetcode-cn.com/problems/path-with-minimum-effort/solution/dpzui-duan-lu-suan-fa-by-oshdyr-s8wg/
*
* @author tobin
* @since 2021-01-29
*/
public class PathWithMinimumEffort {
public static void main(String[] args) {
PathWithMinimumEffort sol = new PathWithMinimumEffort();
// int[][] input = new int[][]{{1, 10, 6, 7, 9, 10, 4, 9}};
int[][] input = new int[][]{{1, 2, 2}, {3, 8, 2}, {5, 3, 5}};
System.out.println(sol.minimumEffortPath(input));
}
public int minimumEffortPath(int[][] heights) {
Queue<Node> q = new LinkedTransferQueue<>();
int rows = heights.length;
int cols = heights[0].length;
int[][] weights = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
weights[i][j] = Integer.MAX_VALUE;
}
}
weights[0][0] = 0; // E1
int[][] directs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
q.add(new Node(0, 0, 0));
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr.weight > weights[curr.x][curr.y]) {
continue;
}
for (int i = 0; i < 4; i++) {
int n_x = curr.x + directs[i][0];
int n_y = curr.y + directs[i][1];
if (n_x >= 0 && n_x < rows
&& n_y >= 0 && n_y < cols) {
int n_weight = Math.abs(heights[curr.x][curr.y] - heights[n_x][n_y]);
n_weight = Math.max(n_weight, curr.weight); // E2
if (n_weight < weights[n_x][n_y]) {
weights[n_x][n_y] = n_weight;
q.add(new Node(n_x, n_y, n_weight));
}
}
}
}
return weights[rows - 1][cols - 1];
}
class Node {
public int x;
public int y;
public int weight;
public Node(int x, int y, int weight) {
this.x = x;
this.y = y;
this.weight = weight;
}
}
}