![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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: