githubEdit

19. Path With Minimum Effort

βœ… GFG solution to the Path With Minimum Effort problem: find minimum cost path where cost is maximum absolute difference between consecutive cells using Dijkstra's algorithm. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given a 2D array mat[][] of size n*m. Your task is to find the minimum possible path cost from the top-left cell (0, 0) to the bottom-right cell (n-1, m-1) by moving up, down, left, or right between adjacent cells.

Note: The cost of a path is defined as the maximum absolute difference between the values of any two consecutive cells along that path.

πŸ“˜ Examples

Example 1

Input: mat[][] = [[7, 2, 6, 5],
                  [3, 1, 10, 8]]
Output: 4
Explanation: The route of [7, 3, 1, 2, 6, 5, 8] has a minimum value of maximum absolute 
difference between any two consecutive cells in the route, i.e., 4.

Example 2

Input: mat[][] = [[2, 2, 2, 1],
                  [8, 1, 2, 7],
                  [2, 2, 2, 8],
                  [2, 1, 4, 7],
                  [2, 2, 2, 2]]
Output: 0
Explanation: The route of [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] has a minimum value of 
maximum absolute difference between any two consecutive cells in the route, i.e., 0.

πŸ”’ Constraints

  • $1 \le n, m \le 100$

  • $0 \le \text{mat}[i][j] \le 10^6$

βœ… My Approach

The optimal approach uses Dijkstra's Algorithm with a Priority Queue to find the path with minimum effort:

Dijkstra's Algorithm with Modified Cost

  1. Initialize Data Structures:

    • Create a dist array initialized with infinity (1e9) to track minimum effort to reach each cell.

    • Use a min-heap priority queue storing tuples of (effort, x-coordinate, y-coordinate).

    • Start from (0, 0) with effort 0.

  2. Process Cells:

    • Pop the cell with minimum effort from priority queue.

    • If destination (n-1, m-1) is reached, return the effort.

    • Skip if current effort is greater than recorded distance (already processed optimally).

  3. Explore Neighbors:

    • For each of 4 directions (up, down, left, right):

      • Calculate new effort as maximum of current effort and absolute difference with neighbor.

      • If new effort is less than recorded distance for neighbor, update and push to queue.

  4. Cost Calculation:

    • Path cost = maximum absolute difference encountered along the entire path.

    • Update using: new_effort = max(current_effort, abs(mat[next] - mat[current])).

  5. Return Result:

    • Return the minimum effort recorded for destination cell.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n Γ— m Γ— log(n Γ— m)), where n and m are the dimensions of the matrix. Each cell is processed at most once, and priority queue operations take O(log(n Γ— m)) time. In the worst case, we may push each cell into the priority queue multiple times before finding the optimal path.

  • Expected Auxiliary Space Complexity: O(n Γ— m), as we maintain a distance array of size n Γ— m and the priority queue can hold at most O(n Γ— m) elements in the worst case.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Binary Search + BFS Approach

πŸ’‘ Algorithm Steps:

  1. Binary search on the answer range from 0 to maximum possible difference.

  2. For each mid value, check if we can reach destination with max cost ≀ mid.

  3. Use BFS to verify if a path exists with the given cost constraint.

  4. Narrow down the search space based on whether path exists or not.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nmlog(max_val)) - Binary search with BFS traversal

  • Auxiliary Space: πŸ’Ύ O(n*m) - Visited array for BFS

βœ… Why This Approach?

  • Efficient when answer range is large

  • Clear separation of concerns with helper function

  • Predictable memory usage pattern

πŸ“Š 3️⃣ Modified Dijkstra with Array

πŸ’‘ Algorithm Steps:

  1. Use tuple with cost stored first for natural ordering in priority queue.

  2. Track visited cells to avoid redundant processing.

  3. Early termination when destination is reached from priority queue.

  4. Compact representation using array initialization for directions.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nmlog(n*m)) - Priority queue operations dominate

  • Auxiliary Space: πŸ’Ύ O(n*m) - Cost array and priority queue

βœ… Why This Approach?

  • Cleaner syntax with array and structured bindings

  • More readable direction handling

  • Standard Dijkstra pattern with modern C++ features

πŸ“Š 4️⃣ Dynamic Programming Bottom-Up

πŸ’‘ Algorithm Steps:

  1. Process cells in multiple passes to propagate minimum costs.

  2. For each cell, update neighbors based on current minimum cost.

  3. Repeat until no updates occur indicating convergence.

  4. Return the cost at destination cell after stabilization.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nmk) - k is number of iterations until convergence

  • Auxiliary Space: πŸ’Ύ O(n*m) - DP table only

βœ… Why This Approach?

  • No priority queue or complex data structures

  • Iterative relaxation similar to Bellman-Ford

  • Good for teaching shortest path concepts

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1110/1115 test cases due to time constraints).

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Dijkstra's Algorithm

🟑 O(nmlog(n*m))

🟒 O(n*m)

πŸš€ Guaranteed optimal solution

πŸ”§ Priority queue overhead

πŸ” Binary Search + BFS

🟑 O(nmlog(max))

🟒 O(n*m)

πŸ“– Works well for large ranges

πŸ’Ύ Multiple complete traversals

πŸ“Š Modified Dijkstra

🟑 O(nmlog(n*m))

🟒 O(n*m)

🎯 Clean modern C++ syntax

🐌 Similar performance to basic

πŸ”„ DP Bottom-Up

πŸ”΄ O(nmk)

🟒 O(n*m)

⭐ Simple iterative approach

πŸ”§ Unpredictable iterations

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… General optimal solution

πŸ₯‡ Dijkstra's Algorithm

β˜…β˜…β˜…β˜…β˜…

πŸ“– Large value ranges

πŸ₯ˆ Binary Search + BFS

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Modern C++ preferred

πŸ₯‰ Modified Dijkstra

β˜…β˜…β˜…β˜…β˜…

🎯 Educational/Simple logic

πŸ… DP Bottom-Up

β˜…β˜…β˜…β˜†β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated