|
1 | 1 | class Solution {
|
| 2 | + |
| 3 | + private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 4 | + |
2 | 5 | 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); |
| 6 | + if (heights.length == 1 && heights[0].length == 1) { |
| 7 | + return 0; |
9 | 8 | }
|
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; |
| 9 | + int leftBound = 0; |
| 10 | + int rightBound = 1000000; |
| 11 | + while (leftBound < rightBound) { |
| 12 | + int mid = (leftBound + rightBound) / 2; |
| 13 | + if (connected(heights, mid)) { |
| 14 | + rightBound = mid; |
| 15 | + } else { |
| 16 | + leftBound = mid + 1; |
19 | 17 | }
|
20 |
| - if (x == rows - 1 && y == cols - 1) { |
21 |
| - return currDistance; |
| 18 | + } |
| 19 | + return leftBound; |
| 20 | + } |
| 21 | + |
| 22 | + private boolean connected(int[][] heights, int targetEffort) { |
| 23 | + int numRows = heights.length; |
| 24 | + int numCols = heights[0].length; |
| 25 | + Queue<int[]> queue = new LinkedList<>(); |
| 26 | + boolean[][] seen = new boolean[numRows][numCols]; |
| 27 | + queue.add(new int[]{0, 0}); |
| 28 | + seen[0][0] = true; |
| 29 | + while (!queue.isEmpty()) { |
| 30 | + int[] removed = queue.remove(); |
| 31 | + int x = removed[0]; |
| 32 | + int y = removed[1]; |
| 33 | + if (x == numRows - 1 && y == numCols - 1) { |
| 34 | + return true; |
22 | 35 | }
|
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}); |
| 36 | + for (int[] dir : DIRS) { |
| 37 | + int newX = x + dir[0]; |
| 38 | + int newY = y + dir[1]; |
| 39 | + if (newX >= 0 && newY >= 0 && newX < numRows && newY < numCols && !seen[newX][newY] && Math.abs(heights[x][y] - heights[newX][newY]) <= targetEffort) { |
| 40 | + queue.add(new int[]{newX, newY}); |
| 41 | + seen[newX][newY] = true; |
33 | 42 | }
|
34 | 43 | }
|
35 | 44 | }
|
36 |
| - return -1; |
| 45 | + return false; |
37 | 46 | }
|
38 | 47 | }
|
0 commit comments