Approach
Breadth-first search
For Path With Minimum Effort, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 43 lines of Java from the credited upstream file 1631.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minimumEffortPath(int[][] heights) {3 4 record T(int i, int j, int d) {}5 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};6 final int m = heights.length;7 final int n = heights[0].length;8 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::d));9 10 int[][] diff = new int[m][n];11 Arrays.stream(diff).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));12 boolean[][] seen = new boolean[m][n];13 14 minHeap.offer(new T(0, 0, 0));15 diff[0][0] = 0;16 17 while (!minHeap.isEmpty()) {18 final int i = minHeap.peek().i;19 final int j = minHeap.peek().j;20 final int d = minHeap.poll().d;21 if (i == m - 1 && j == n - 1)22 return d;23 seen[i][j] = true;24 for (int[] dir : DIRS) {25 final int x = i + dir[0];26 final int y = j + dir[1];27 if (x < 0 || x == m || y < 0 || y == n)28 continue;29 if (seen[x][y])30 continue;31 final int newDiff = Math.abs(heights[i][j] - heights[x][y]);32 final int maxDiff = Math.max(diff[i][j], newDiff);33 if (diff[x][y] > maxDiff) {34 diff[x][y] = maxDiff;35 minHeap.offer(new T(x, y, maxDiff));36 }37 }38 }39 40 throw new IllegalArgumentException();41 }42}43