02. Minimum Cost Path

The problem can be found at the following link: Question Link

Note: Sorry for uploading late, my exam is going on.

Problem Description

Given a square grid of size N, each cell of which contains an integer cost representing the cost to traverse through that cell, we need to find a path from the top-left cell to the bottom-right cell such that the total cost incurred is minimized. From the cell (i,j), you can move to (i,j-1), (i,j+1), (i-1,j), or (i+1,j).

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.

Input:

grid = {{4,4},{3,7}}

Output:

14

Explanation: The minimum cost path is 4 -> 3 -> 7.

My Approach

  1. Dijkstra's Algorithm:

    • This problem can be visualized as a graph traversal problem where each cell is a node, and each move from a cell to its adjacent cell is an edge with a weight equal to the cost of the destination cell.

  2. Priority Queue for Optimality:

    • A priority queue (min-heap) is used to explore paths with the lowest cost first. The priority queue stores cells along with their current cumulative cost.

  3. Dynamic Programming for Storing Minimum Costs:

    • A 2D DP array dp is used where dp[i][j] holds the minimum cost to reach cell (i, j) from the starting cell (0, 0).

  4. Exploration of Adjacent Cells:

    • For each cell (i, j) dequeued from the priority queue, the algorithm checks its adjacent cells. If moving to an adjacent cell offers a lower cost than previously recorded, the DP array is updated, and the adjacent cell is enqueued with the new cumulative cost.

  5. Final Answer:

    • The minimum cost to reach the bottom-right cell (n-1, m-1) is stored in dp[n-1][m-1].

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n² * log(n)), as we are using Dijkstra's algorithm with a priority queue, which takes O(log(n)) time for each operation, and there are nodes.

  • Expected Auxiliary Space Complexity: O(n²), for storing the DP array and the priority queue.

Code (C++)

Code (Java)

Sometime Its Not Running Python(Code) But I've Tried Its Prefectly Running

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.

⭐ Star this repository if you find it helpful or intriguing! ⭐


📍Visitor Count

Last updated