Skip to content

Commit f2770aa

Browse files
authored
Added Path With Minimum Effort.java
1 parent 17ed31f commit f2770aa

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Medium/Path With Minimum Effort.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public int minimumEffortPath(int[][] heights) {
3+
int rows = heights.length;
4+
int cols = heights[0].length;
5+
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
6+
int[][] distance = new int[rows][cols];
7+
for (int i = 0; i < rows; i++) {
8+
Arrays.fill(distance[i], Integer.MAX_VALUE);
9+
}
10+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
11+
pq.add(new int[]{0, 0, 0});
12+
while (!pq.isEmpty()) {
13+
int[] removed = pq.poll();
14+
int currDistance = removed[0];
15+
int x = removed[1];
16+
int y = removed[2];
17+
if (currDistance > distance[x][y]) {
18+
continue;
19+
}
20+
if (x == rows - 1 && y == cols - 1) {
21+
return currDistance;
22+
}
23+
for (int[] direction : directions) {
24+
int newX = x + direction[0];
25+
int newY = y + direction[1];
26+
if (newX < 0 || newX >= rows || newY < 0 || newY >= cols) {
27+
continue;
28+
}
29+
int newDistance = Math.max(currDistance, Math.abs(heights[newX][newY] - heights[x][y]));
30+
if (distance[newX][newY] > newDistance) {
31+
distance[newX][newY] = newDistance;
32+
pq.add(new int[]{newDistance, newX, newY});
33+
}
34+
}
35+
}
36+
return -1;
37+
}
38+
}

0 commit comments

Comments
 (0)