9
Tuple(int distance, int row, int col) {11
this.distance = distance;21
public int minimumEffortPath(int[][] heights) {23
// Create a min heap based on the distance25
PriorityQueue<Tuple> minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);27
int rows = heights.length;29
int cols = heights[0].length;31
// Create a 2D array to store the minimum effort to reach each cell33
int effort[][] = new int[rows][cols];35
// Initialize all efforts to maximum initially37
for (int i = 0; i < rows; i++) {39
Arrays.fill(effort[i], Integer.MAX_VALUE);42
effort[0][0] = 0; // Initial effort at the starting cell44
// Add the starting cell to the min heap46
minHeap.add(new Tuple(0, 0, 0));48
// Arrays to represent row and column changes for 4 directions50
int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left52
int dc[] = {0, 1, 0, -1};54
while (!minHeap.isEmpty()) {56
Tuple current = minHeap.poll(); // Get the cell with the minimum effort58
int distance = current.distance;60
int row = current.row;62
int col = current.col;64
if (row == rows - 1 && col == cols - 1) {66
return distance; // If reached the destination, return the effort69
// Explore each of the 4 possible directions71
for (int i = 0; i < 4; i++) {73
int newRow = row + dr[i]; // Calculate new row index75
int newCol = col + dc[i]; // Calculate new column index77
// Check if the new cell is within bounds79
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {81
// Calculate the new effort based on the maximum of height difference and current effort83
int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);85
// If the new effort is less than the stored effort for the cell, update and add to heap87
if (newEffort < effort[newRow][newCol]) {89
effort[newRow][newCol] = newEffort;92
new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration98
return 0; // This value should be replaced with the actual minimum effort