Leetcode-editorials
Contribute
  • Leetcode question of the day
  • 08-August
    • 26. Maximum Length of Pair Chain
    • 28. Implement stack using queues
    • 29. Minimum Penalty for a Shop
    • 30. Minimum Replacements to Sort the Array
    • 31. Minimum Number of Taps to Open to Water a Garden
  • 09-September
    • 01. Counting Bits
    • 02. Extra Characters in a String
    • 03. Unique Paths
    • 04. Linked List Cycle
    • 05. Copy List with Random Pointer
    • 06. Split Linked List in Parts
    • 07. Reverse Linked List II
    • 08. Pascal's Triangle
    • 09. Combination Sum IV
    • 10. Count All Valid Pickup and Delivery Options
    • 11. Group the People Given the Group Size They Belong To
    • 12. Minimum Deletions to Make Character Frequencies Unique
    • 13. Candy
    • 14. Reconstruct Itinerary
    • 15. Min Cost to Connect All Points
    • 16. Path With Minimum Effort
    • 17. Shortest Path Visiting All Nodes
    • 18. The K Weakest Rows in a Matrix
    • 19. Find the Duplicate Number
    • 20. Minimum Operations to Reduce X to Zero
    • 21-Median of Two Sorted Arrays
    • 22- Is Subsequence
    • 23- Longest String Chain
    • 24- Champagne Tower
    • 25- Find the Difference
    • 26- Remove Duplicate Letters
    • 27- Decoded String at Index
    • 28- Sort Array By Parity
    • 29- Monotonic Array
    • 30- 132 Pattern
  • 10-October
    • 01. Reverse Words in a String III
    • 02. Remove Colored Pieces if Both Neighbors are the Same Color
    • 03. Number of Good Pairs
    • 04. Design HashMap
    • 05. Majority Element II
    • 06. Integer Break
    • 07. Build Array Where You Can Find The Maximum Exactly K Comparisons
  • 11-November
    • 01. Find Mode in Binary Search Tree
    • 02. Count Nodes Equal to Average of Subtree
    • 03. Build an Array With Stack Operations
    • 04. Last Moment Before All Ants Fall Out of a Plank
    • 07. Eliminate Maximum Number of Monsters
  • Leetcode Contests
    • Weekly Contest
      • Weekly-Contest-360
Powered by GitBook
On this page
  • My Approach
  • Time and Auxiliary Space Complexity
  • Code (C++)
  • Contribution and Support

Was this helpful?

Edit on GitHub
  1. 09-September

16. Path With Minimum Effort

Previous15. Min Cost to Connect All PointsNext17. Shortest Path Visiting All Nodes

Last updated 1 year ago

Was this helpful?

The problem can be found at the following link:

My Approach

  1. Start by defining a class named Solution with a public member function minimumEffortPath, which takes a 2D vector heights as input and returns an integer.

  2. Get the dimensions of the heights grid: m represents the number of rows, and n represents the number of columns.

  3. Check if the grid has only one cell (m == 1 and n == 1), return 0 as there is no effort required to move within a single-cell grid.

  4. Create a 2D vector dist of size m x n to store the minimum effort required to reach each cell from the starting cell. Initialize all values in dist to INT_MAX except for the starting cell, which is set to 0.

  5. Create a priority_queue named pq to store cells as pairs of (distance, cell), where distance represents the minimum effort to reach that cell, and the cell is represented as (i, j).

  6. Define two vectors, di and dj, to represent the four possible directions to move: up, left, down, and right. These vectors will be used to explore neighboring cells.

  7. Start a while loop that continues as long as the priority queue pq is not empty.

  8. Inside the loop, pop the top element from pq, which represents the cell with the smallest effort required.

  9. Extract the row i and column j of the current cell from the popped element.

  10. Iterate through the four possible directions (up, left, down, right) using a for loop.

  11. For each direction, calculate the new row ni and new column nj by adding the corresponding values from di and dj to the current row i and column j.

  12. Check if the new cell (ni, nj) is within the boundaries of the grid (i.e., ni >= 0, nj >= 0, ni < m, and nj < n).

  13. Calculate the new distance newDist required to reach the new cell. This distance is the maximum of the current distance dist[i][j] and the absolute difference in heights between the current cell and the new cell abs(heights[i][j] - heights[ni][nj]).

  14. If the new distance newDist is smaller than the current distance dist[ni][nj], update dist[ni][nj] with newDist and push the new cell (ni, nj) into the priority queue pq with the updated distance.

  15. Repeat steps 8-14 until all cells have been processed, ensuring that the priority queue always contains cells with the minimum effort.

  16. Finally, return the minimum effort required to reach the bottom-right cell, which is stored in dist[m - 1][n - 1].

This algorithm uses Dijkstra's algorithm with a priority queue to find the minimum effort path from the top-left corner to the bottom-right corner of the grid while considering the differences in heights between adjacent cells.

Time and Auxiliary Space Complexity

  • Time Complexity: O(m*n*log(m*n))

  • Auxiliary Space Complexity: O(m*n)

Code (C++)


class Solution {
public:
    int minimumEffortPath(std::vector<std::vector<int>>& heights) {
        int m = heights.size();
        int n = heights[0].size();
        if (m == 1 && n == 1) {
            return 0;
        }

        vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
        dist[0][0] = 0;


        priority_queue<pair<int, int>, vector<pair<int, int>>,greater<pair<int, int>>> pq;
        pq.push({0, 0});
  
        vector<int> di = {-1, 0, 1, 0};
        vector<int> dj = {0, -1, 0, 1};

        while (!pq.empty()) {
            auto it = pq.top();
            pq.pop();
            int i = it.first;
            int j = it.second;

            for (int k = 0; k < 4; k++) {
                int ni = i + di[k];
                int nj = j + dj[k];

                if (ni >= 0 && nj >= 0 && ni < m && nj < n) {

                    // Important logic of the entire code
                    int newDist = max(dist[i][j], abs(heights[i][j] - heights[ni][nj]));

                    // If we found a shorter path, update distance and push to priority queue
                    if (newDist < dist[ni][nj]) {
                        dist[ni][nj] = newDist;
                        pq.push({ni, nj});
                    }
                }
            }
        }
        return dist[m - 1][n - 1];
    }
};

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.

Question Link
discussion section
rishabhv12/Daily-Leetcode-Solution