VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-path-left-right-bottom-moves-allowed/

⇱ Minimum Cost Path with Left, Right, Bottom and Up moves allowed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Cost Path with Left, Right, Bottom and Up moves allowed

Last Updated : 23 Jan, 2025

Given a 2D grid of size n*n, where each cell represents the cost to traverse through that cell, the task is to find the minimum cost to move from the top left cell to the bottom right cell. From a given cell, we can move in 4 directions: left, right, up, down.

Note: It is assumed that negative cost cycles do not exist in input matrix.

Example:

Input: grid = {{9, 4, 9, 9},
{6, 7, 6, 4},
{8, 3, 3, 7},
{7, 4, 9, 10}}
Output: 43
Explanation: The minimum cost path is 9 + 4 + 7 + 3 + 3 + 7 + 10.

Approach:

The idea is to use Dijkstra's algorithm to find the minimum cost path through the grid. This approach treats the grid as a graph where each cell is a node, and the algorithm dynamically explores the most cost-effective path to the bottom-right cell by always expanding the lowest-cost paths first.

Step by step approach:

  1. Use a min-heap to always process the lowest-cost path first and push the top left cell into it.
  2. Initialize a cost matrix with maximum values, setting the start cell's cost to its grid value.
  3. For each cell, check all 4 neighboring cells
    1. If a lower cost path is found, then update the cost of cell and push it into heap.
  4. Return the minimum cost to reach the bottom-right cell.

Below is the implementation of the above approach:


Output
43

Time Complexity: O(n^2 log(n^2))
Auxiliary Space: O(n^2 log(n^2))

Why dynamic programming cannot be used?

Dynamic programming fails here because allowing movement in all four directions creates cycles where cells can be revisited, breaking the optimal substructure assumption. This means the cost to reach a cell from a given cell isn't fixed but depends on the entire path.

Related Articles:

Min Cost Path

Comment
Article Tags:
Article Tags: