The Wayback Machine - https://web.archive.org/web/20241220085551/https://www.geeksforgeeks.org/min-cost-path-dp-6/
Open In App

Min Cost Path

Last Updated : 03 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a 2d matrix cost[][], the task is to calculate the minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination).
We can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1), and (i+1, j+1) can be traversed.

Example:

Input:

Min-Cost-Path-1

Output: 8
Explanation: The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).  

Min-Cost-Path-2

Using Recursion – O(3^(m+n)) Time and O(m+n) Space

For the recursive approach, there are three potential cases for each cell in the grid (for any cell at position (m, n)):

  • The cost to reach the current cell can be calculated by moving left, i.e., from cell (m, n-1).
  • The cost to reach the current cell can also be calculated by moving up, i.e., from cell (m-1, n).
  • The cost can also be calculated by moving diagonally, i.e., from cell (m-1, n-1).

Mathematically, the recurrence relation will look like:

minCost(cost, m, n) = cost[m][n] + min(minCost(cost, m, n-1), minCost(cost, m-1, n), minCost(cost, m-1, n-1))

Base Cases:

  • if m < 0 or n < 0 (out of bounds) minCost(cost, m, n) = INT_MAX
  • minCost(cost, 0, 0) = cost[0][0] as the starting point.
C++
// C++ implementation to find the minimum cost path
// using Recursion
#include <bits/stdc++.h>
using namespace std;

// Function to return the cost of the minimum cost path
// from (0,0) to (m, n) in a cost matrix
int minCost(vector<vector<int>>& cost, int m, int n) {
  
    // If indices are out of bounds, return a large value
    if (m < 0 || n < 0) {
        return INT_MAX;
    }
    // Base case: starting cell
    if (m == 0 && n == 0) {
        return cost[m][n];
    }

    // Recursively calculate minimum cost from 
    // all possible paths
    return cost[m][n] + min({minCost(cost, m, n - 1), 
                             minCost(cost, m - 1, n), 
                             minCost(cost, m - 1, n - 1)}); 
}

int main() {
  
    vector<vector<int>> cost = { { 1, 2, 3 },
                                 { 4, 8, 2 },
                                 { 1, 5, 3 } };
  
    int m = cost.size();
    int n = cost[0].size();
  
    cout << minCost(cost, m-1, n-1) << endl;

    return 0;
}
Java
// Java implementation to find the minimum cost path
// using Recursion
import java.util.ArrayList;
import java.util.List;

class GfG {

    // Function to return the cost of the minimum cost path
    // from (0,0) to (m, n) in a cost matrix
    static int minCost(List<List<Integer>> cost, int m, int n) {
      
        // If indices are out of bounds, return a large value
        if (m < 0 || n < 0) {
            return Integer.MAX_VALUE;
        }
        // Base case: starting cell
        if (m == 0 && n == 0) {
            return cost.get(m).get(n);
        }

        // Recursively calculate minimum cost from
        // all possible paths
        return cost.get(m).get(n) + Math.min(
                Math.min(minCost(cost, m, n - 1),
                         minCost(cost, m - 1, n)),
                minCost(cost, m - 1, n - 1));
    }

    public static void main(String[] args) {
      
        List<List<Integer>> cost = new ArrayList<>();
        cost.add(new ArrayList<>(List.of(1, 2, 3)));
        cost.add(new ArrayList<>(List.of(4, 8, 2)));
        cost.add(new ArrayList<>(List.of(1, 5, 3)));
      
        int m = cost.size();
        int n = cost.get(0).size();
        System.out.println(minCost(cost, m-1, n-1));
    }
}
Python
# Python implementation to find the minimum cost path
# using Recursion

# Function to return the cost of the minimum cost path
# from (0,0) to (m, n) in a cost matrix
def minCost(cost, m, n):
  
    # If indices are out of bounds, return a large value
    if m < 0 or n < 0:
        return float('inf')
      
    # Base case: starting cell
    if m == 0 and n == 0:
        return cost[m][n]

    # Recursively calculate minimum cost from
    # all possible paths
    return cost[m][n] + min(
        minCost(cost, m, n - 1), 
        minCost(cost, m - 1, n), 
        minCost(cost, m - 1, n - 1) 
    )

if __name__ == "__main__":
  
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]

    m = len(cost)
    n = len(cost[0])

    print(minCost(cost, m-1, n-1))
C#
// C# implementation to find the minimum cost path
// using Recursion
using System;
using System.Collections.Generic;

class GfG {

    // Function to return the cost of the minimum cost path
    // from (0,0) to (m, n) in a cost matrix
    static int MinCost(List<List<int>> cost, int m, int n) {

        // If indices are out of bounds, return a large value
        if (m < 0 || n < 0) {
            return int.MaxValue;
        }
      
        // Base case: starting cell
        if (m == 0 && n == 0) {
            return cost[m][n];
        }

        // Recursively calculate minimum cost from
        // all possible paths
        return cost[m][n] + Math.Min(
                Math.Min(MinCost(cost, m, n - 1),
                         MinCost(cost, m - 1, n)),
                MinCost(cost, m - 1, n - 1));
    }

    static void Main() {

        List<List<int>> cost = new List<List<int>>() {
            new List<int>() { 1, 2, 3 },
            new List<int>() { 4, 8, 2 },
            new List<int>() { 1, 5, 3 }
        };
      
        int m = cost.Count;
        int n = cost[0].Count;
      
        Console.WriteLine(MinCost(cost, m-1, n-1));
    }
}
JavaScript
// JavaScript implementation to find the minimum cost path
// using Recursion

// Function to return the cost of the minimum cost path
// from (0,0) to (m, n) in a cost matrix
function minCost(cost, m, n) {

    // If indices are out of bounds, return a large value
    if (m < 0 || n < 0) {
        return Number.MAX_VALUE;
    }
    
    // Base case: starting cell
    if (m === 0 && n === 0) {
        return cost[m][n];
    }

    // Recursively calculate minimum cost from
    // all possible paths
    return cost[m][n] + Math.min(
        minCost(cost, m, n - 1), 
        minCost(cost, m - 1, n), 
        minCost(cost, m - 1, n - 1) 
    );
}

const cost = [
    [1, 2, 3],
    [4, 8, 2],
    [1, 5, 3]
];

const m = cost.length;
const n = cost[0].length;
console.log(minCost(cost, m-1, n-1));

Output
8

Using Top-Down DP (Memoization) – O(m*n) Time and O(m*n) Space

1. Optimal Substructure:The minimum cost to reach any cell in the grid can be derived from smaller subproblems (i.e., the cost to reach neighboring cells). Specifically, the recursive relation will look like:

minCost(cost, m, n) = cost[m][n] + min(minCost(cost, m, n-1), minCost(cost, m-1, n), minCost(cost, m-1, n-1))

If the last element (i.e., cell (m, n)) is reached, the cost to reach it will be the value of the cell plus the minimum cost to reach one of its valid neighboring cells (left, up, or diagonal).

2. Overlapping Subproblems:

minCost

In the recursive approach, subproblems are computed multiple times. For example, when computing the minimum cost from (m, n), we may need to compute the cost for (m-1, n) multiple times. This repetition can be avoided by storing the results of subproblems in a memoization table.

memo[m][n] = cost[m][n] + min(minCost(cost, m, n-1), minCost(cost, m-1, n), minCost(cost, m-1, n-1))

Steps to implement Memoization:

  • Create a 2D memo table of size (m x n) to store the computed values, initialized to -1 to indicate uncomputed subproblems.
  • If we are at the starting cell (0, 0), return the value of cost[0][0].
  • Before computing the result for any cell (m, n), check if the value at memo[m][n] is already computed. If it is, return the stored value.
  • If the value is not computed, recursively calculate the minimum cost and store it in memo[m][n].
  • Finally, return the value in memo[m][n] for the minimum cost to reach the target cell (m-1, n-1).
C++
// C++ implementation to find the minimum cost path
// using Recursion with Memoization
#include <bits/stdc++.h>
using namespace std;

// Function to return the cost of the minimum cost path
int minCost(vector<vector<int>>& cost, int m, int n,
            vector<vector<int>>& memo) {

    // If indices are out of bounds, return a large value
    if (m < 0 || n < 0) {
        return INT_MAX;
    }
    // Base case: starting cell
    if (m == 0 && n == 0) {
        return cost[m][n];
    }
    // Return precomputed value if available
    if (memo[m][n] != -1) {
        return memo[m][n];
    }

    // Compute and store the result
    memo[m][n] = cost[m][n] + min({minCost(cost, m, n - 1, memo),
                                   minCost(cost, m - 1, n, memo),
                                   minCost(cost, m - 1, n - 1, memo)});
    return memo[m][n];
}

int main() {
  
    vector<vector<int>> cost = { { 1, 2, 3 },
                                 { 4, 8, 2 },
                                 { 1, 5, 3 } };

    int m = cost.size();
    int n = cost[0].size();
    vector<vector<int>> memo(m, vector<int>(n, -1));
    cout << minCost(cost, m - 1, n - 1, memo) << endl;

    return 0;
}
Java
// Java implementation to find the minimum cost path
// using Recursion with Memoization
import java.util.ArrayList;
import java.util.List;

class GfG {

    // Function to return the cost of the minimum cost path
    static int minCost(List<List<Integer>> cost, int m, int n, 
                       int[][] memo) {

        // If indices are out of bounds, return a large value
        if (m < 0 || n < 0) {
            return Integer.MAX_VALUE;
        }
      
        // Base case: starting cell
        if (m == 0 && n == 0) {
            return cost.get(m).get(n);
        }
      
        // Return precomputed value if available
        if (memo[m][n] != -1) {
            return memo[m][n];
        }

        // Compute and store the result
        memo[m][n] = cost.get(m).get(n) + Math.min(
                        Math.min(minCost(cost, m, n - 1, memo), 
                                 minCost(cost, m - 1, n, memo)),
                                 minCost(cost, m - 1, n - 1, memo));
        return memo[m][n];
    }

    public static void main(String[] args) {
      
        List<List<Integer>> cost = new ArrayList<>();
        cost.add(List.of(1, 2, 3));
        cost.add(List.of(4, 8, 2));
        cost.add(List.of(1, 5, 3));

        int m = cost.size();
        int n = cost.get(0).size();

        int[][] memo = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                memo[i][j] = -1;
            }
        }
      
        System.out.println(minCost(cost, m - 1, n - 1, memo));
    }
}
Python
# Python implementation to find the minimum cost path
# using Recursion with Memoization

def mincost(cost, m, n, memo):
  
    # If indices are out of bounds, 
    # return a large value
    if m < 0 or n < 0:
        return float('inf')
      
    # Base case: starting cell
    if m == 0 and n == 0:
        return cost[m][n]
      
    # Return precomputed value if available
    if memo[m][n] != -1:
        return memo[m][n]

    # Compute and store the result
    memo[m][n] = cost[m][n] + min(
        mincost(cost, m, n - 1, memo),
        mincost(cost, m - 1, n, memo),
        mincost(cost, m - 1, n - 1, memo),
    )
    return memo[m][n]

if __name__ == "__main__":
  
    # Hardcoded cost matrix
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3],
    ]

    m = len(cost)
    n = len(cost[0])

    memo = [[-1 for i in range(n)] for i in range(m)]
    print(mincost(cost, m - 1, n - 1, memo))
C#
// C# implementation to find the minimum cost path
// using Recursion with Memoization
using System;
using System.Collections.Generic;

class GfG {

    // Function to return the cost of the minimum cost path
    static int MinCost(List<List<int>> cost, 
                         int m, int n, int[,] memo) {

        // If indices are out of bounds, return a large value
        if (m < 0 || n < 0) {
            return int.MaxValue;
        }
        // Base case: starting cell
        if (m == 0 && n == 0) {
            return cost[m][n];
        }
        // Return precomputed value if available
        if (memo[m, n] != -1) {
            return memo[m, n];
        }

        // Compute and store the result
        memo[m, n] = cost[m][n] + Math.Min(
                        Math.Min(MinCost(cost, m, n - 1, memo),
                                 MinCost(cost, m - 1, n, memo)),
                                 MinCost(cost, m - 1, n - 1, memo));
        return memo[m, n];
    }

    static void Main(string[] args) {

        List<List<int>> cost = new List<List<int>> {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 8, 2 },
            new List<int> { 1, 5, 3 }
        };

        int m = cost.Count;
        int n = cost[0].Count;
        int[,] memo = new int[m, n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                memo[i, j] = -1;
            }
        }

        Console.WriteLine(MinCost(cost, m - 1, n - 1, memo));
    }
}
JavaScript
// Javascript implementation to find the minimum cost path
// using Recursion with Memoization

function minCost(cost, m, n, memo) {

    // If indices are out of bounds, return a large value
    if (m < 0 || n < 0) return Infinity;
    
    // Base case: starting cell
    if (m === 0 && n === 0) return cost[m][n];
    
    // Return precomputed value if available
    if (memo[m][n] !== -1) return memo[m][n];

    // Compute and store the result
    memo[m][n] = cost[m][n] + Math.min(
        minCost(cost, m, n - 1, memo),
        minCost(cost, m - 1, n, memo),
        minCost(cost, m - 1, n - 1, memo)
    );
    return memo[m][n];
}

// Hardcoded cost matrix
const cost = [
    [1, 2, 3],
    [4, 8, 2],
    [1, 5, 3]
];

const m = cost.length;
const n = cost[0].length;

const memo = Array.from({ length: m }, () => Array(n).fill(-1));
console.log(minCost(cost, m - 1, n - 1, memo));

Output
8

Using Bottom-Up DP (Tabulation) – O(m*n) Time and O(m*n) Space

The approach here is similar to the recursive one but instead of breaking down the problem recursively, we iteratively build up the solution by calculating it in a bottom-up manner. We create a 2D array dp of size m*n where dp[i][j] represents the minimum cost to reach cell (i, j).

Dynamic Programming Relation:

Initialize the base case: dp[0][0] = cost[0][0]

  • For the first row (dp[0][j]), we can only move from the left: dp[0][j] = dp[0][j – 1] + cost[0][j] for j > 0
  • For the first column (dp[i][0]), we can only move from the top: dp[i][0] = dp[i – 1][0] + cost[i][0] for i > 0

For the rest of the cells, we calculate the minimum cost by considering the minimum cost from three directions: from the left, from above, and from the diagonal:

  • dp[i][j] = cost[i][j] + min(dp[i – 1][j], dp[i][j – 1], dp[i – 1][j – 1])

This formula ensures that at each step, we are choosing the minimum cost path to reach the current cell.

C++
// C++ implementation to find the minimum cost path
// using Tabulation (Dynamic Programming)
#include <bits/stdc++.h>
using namespace std;

int minCost(vector<vector<int>>& cost) {
    int m = cost.size();
    int n = cost[0].size();
    
    vector<vector<int>> dp(m, vector<int>(n, 0));
    
    // Initialize the base cell
    dp[0][0] = cost[0][0];

    // Fill the first row
    for (int j = 1; j < n; j++) {
        dp[0][j] = dp[0][j - 1] + cost[0][j];
    }

    // Fill the first column
    for (int i = 1; i < m; i++) {
        dp[i][0] = dp[i - 1][0] + cost[i][0];
    }

    // Fill the rest of the dp table
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = cost[i][j] 
                          + min({dp[i - 1][j],
                              dp[i][j - 1], dp[i - 1][j - 1]});
        }
    }

    return dp[m - 1][n - 1];
}

int main() {
  
    vector<vector<int>> cost = {
        {1, 2, 3},
        {4, 8, 2},
        {1, 5, 3}
    };

    cout << minCost(cost) << endl;
    return 0;
}
Java
// Java implementation to find the minimum cost path
// using Tabulation (Dynamic Programming)
import java.util.ArrayList;
import java.util.List;

class GfG {
  
    static int minCost(List<List<Integer>> cost) {
      
        int m = cost.size();
        int n = cost.get(0).size();
        int[][] dp = new int[m][n];

        // Initialize the base cell
        dp[0][0] = cost.get(0).get(0);

        // Fill the first row
        for (int j = 1; j < n; j++) {
            dp[0][j] = dp[0][j - 1] + cost.get(0).get(j);
        }

        // Fill the first column
        for (int i = 1; i < m; i++) {
            dp[i][0] = dp[i - 1][0] + cost.get(i).get(0);
        }

        // Fill the rest of the dp table
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = cost.get(i).get(j) 
                   + Math.min(dp[i - 1][j], 
                     Math.min(dp[i][j - 1], dp[i - 1][j - 1]));
            }
        }

        // Minimum cost to reach the bottom-right cell
        return dp[m - 1][n - 1];
    }

    public static void main(String[] args) {
      
        List<List<Integer>> cost = new ArrayList<>();
        cost.add(List.of(1, 2, 3));
        cost.add(List.of(4, 8, 2));
        cost.add(List.of(1, 5, 3));

        System.out.println(minCost(cost));
    }
}
Python
# Python implementation to find the minimum cost path
# using Tabulation (Dynamic Programming)

def mincost(cost):
    m = len(cost)
    n = len(cost[0])
    dp = [[0] * n for _ in range(m)]

    # Initialize the base cell
    dp[0][0] = cost[0][0]

    # Fill the first row
    for j in range(1, n):
        dp[0][j] = dp[0][j - 1] + cost[0][j]

    # Fill the first column
    for i in range(1, m):
        dp[i][0] = dp[i - 1][0] + cost[i][0]

    # Fill the rest of the dp table
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = cost[i][j] \
                       + min(dp[i - 1][j], \
                            dp[i][j - 1], dp[i - 1][j - 1])

    # Minimum cost to reach the
    # bottom-right cell
    return dp[m - 1][n - 1]

if __name__ == "__main__":
  
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]
    print(mincost(cost))
C#
// C# implementation to find the minimum cost path
// using Tabulation (Dynamic Programming)
using System;
using System.Collections.Generic;

class GfG {
  
    static int MinCost(List<List<int>> cost) {
        int m = cost.Count;
        int n = cost[0].Count;
        int[,] dp = new int[m, n];

        // Initialize the base cell
        dp[0, 0] = cost[0][0];

        // Fill the first row
        for (int j = 1; j < n; j++) {
            dp[0, j] = dp[0, j - 1] + cost[0][j];
        }

        // Fill the first column
        for (int i = 1; i < m; i++) {
            dp[i, 0] = dp[i - 1, 0] + cost[i][0];
        }

        // Fill the rest of the dp table
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i, j] = cost[i][j]
                         + Math.Min(dp[i - 1, j], 
                              Math.Min(dp[i, j - 1], dp[i - 1, j - 1]));
            }
        }

        // Minimum cost to reach the
          // bottom-right cell
        return dp[m - 1, n - 1];
    }

    static void Main() {

        List<List<int>> cost = new List<List<int>> {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 8, 2 },
            new List<int> { 1, 5, 3 }
        };

        Console.WriteLine(MinCost(cost));
    }
}
JavaScript
// JavaScript implementation to find the minimum cost path
// using Tabulation (Dynamic Programming)

function minCost(cost) {

    const m = cost.length;
    const n = cost[0].length;
    const dp = Array.from({ length: m }, () => Array(n).fill(0));

    // Initialize the base cell
    dp[0][0] = cost[0][0];

    // Fill the first row
    for (let j = 1; j < n; j++) {
        dp[0][j] = dp[0][j - 1] + cost[0][j];
    }

    // Fill the first column
    for (let i = 1; i < m; i++) {
        dp[i][0] = dp[i - 1][0] + cost[i][0];
    }

    // Fill the rest of the dp table
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            dp[i][j] = cost[i][j] 
                    + Math.min(dp[i - 1][j],
                        dp[i][j - 1], dp[i - 1][j - 1]);
        }
    }

    // Minimum cost to reach the bottom-right cell
    return dp[m - 1][n - 1];
}

const cost = [
    [1, 2, 3],
    [4, 8, 2],
    [1, 5, 3]
];
console.log(minCost(cost));

Output
8

Using Space Optimized DP – O(m*n) Time and O(n) Space

In the previous approach, we used a 2D dp table to store the minimum cost at each cell. However, we can optimize the space complexity by observing that for calculating the current state, we only need the values from the previous row. Therefore, there is no need to store the entire dp table, and we can optimize the space to O(n) by only keeping track of the current and previous rows.

C++
// C++ implementation to find the minimum cost path
// using Space Optimization
#include <bits/stdc++.h>
using namespace std;

int minCost(vector<vector<int>> &cost) {
  
    int m = cost.size();
    int n = cost[0].size();

    // 1D dp array to store the minimum cost
      // of the current row
    vector<int> dp(n, 0);

    // Initialize the base cell
    dp[0] = cost[0][0];

    // Fill the first row
    for (int j = 1; j < n; j++) {
        dp[j] = dp[j - 1] + cost[0][j];
    }

    // Fill the rest of the rows
    for (int i = 1; i < m; i++) {
      
        // Store the previous value of dp[j-1] 
          // (for diagonal handling)
        int prev = dp[0];

        // Update the first column (only depends on
          // the previous row)
        dp[0] = dp[0] + cost[i][0];

        for (int j = 1; j < n; j++) {
          
            // Store the current dp[j] before updating it
            int temp = dp[j];

            // Update dp[j] using the minimum of the
              // top, left, and diagonal cells
            dp[j] = cost[i][j] + min({dp[j], dp[j - 1], prev});

            // Update prev to be the old dp[j] for the
              // diagonal calculation in the next iteration
            prev = temp;
        }
    }

    // The last cell contains the 
      // minimum cost path
    return dp[n - 1];
}

int main() {
    vector<vector<int>> cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}};

    cout << minCost(cost) << endl;
    return 0;
}
Java
// Java implementation to find the minimum cost path
// using Space Optimization
import java.util.*;

class GfG {

    static int minCost(int[][] cost) {
        int m = cost.length;
        int n = cost[0].length;

        // 1D dp array to store the minimum cost of the
        // current row
        int[] dp = new int[n];

        // Initialize the base cell
        dp[0] = cost[0][0];

        // Fill the first row
        for (int j = 1; j < n; j++) {
            dp[j] = dp[j - 1] + cost[0][j];
        }

        // Fill the rest of the rows
        for (int i = 1; i < m; i++) {
          
            // Store the previous value of dp[j-1] (for
            // diagonal handling)
            int prev = dp[0];

            // Update the first column (only depends on the
            // previous row)
            dp[0] = dp[0] + cost[i][0];

            for (int j = 1; j < n; j++) {
              
                // Store the current dp[j] before updating
                // it
                int temp = dp[j];

                // Update dp[j] using the minimum of the
                // top, left, and diagonal cells
                dp[j]
                    = cost[i][j]
                      + Math.min(dp[j],
                                 Math.min(dp[j - 1], prev));

                // Update prev to be the old dp[j] for the
                // diagonal calculation in the next
                // iteration
                prev = temp;
            }
        }

        // The last cell contains the minimum cost path
        return dp[n - 1];
    }

    public static void main(String[] args) {
        int[][] cost
            = { { 1, 2, 3 }, { 4, 8, 2 }, { 1, 5, 3 } };

        System.out.println(minCost(cost));
    }
}
Python
# Python implementation to find the minimum cost path
# using Space Optimization
def minCost(cost):
    m = len(cost)
    n = len(cost[0])

    # 1D dp array to store the minimum
    # cost of the current row
    dp = [0] * n

    # Initialize the base cell
    dp[0] = cost[0][0]

    # Fill the first row
    for j in range(1, n):
        dp[j] = dp[j - 1] + cost[0][j]

    # Fill the rest of the rows
    for i in range(1, m):
      
        # Store the previous value of dp[j-1] 
        # (for diagonal handling)
        prev = dp[0]

        # Update the first column (only depends
        # on the previous row)
        dp[0] = dp[0] + cost[i][0]

        for j in range(1, n):
          
            # Store the current dp[j] before
            # updating it
            temp = dp[j]

            # Update dp[j] using the minimum of the top,
            # left, and diagonal cells
            dp[j] = cost[i][j] + min(dp[j], dp[j - 1], prev)

            # Update prev to be the old dp[j] for the 
            # diagonal calculation in the next iteration
            prev = temp

    # The last cell contains the minimum 
    # cost path
    return dp[n - 1]

cost = [
    [1, 2, 3],
    [4, 8, 2],
    [1, 5, 3]
]

print(minCost(cost))
C#
// C# implementation to find the minimum cost path
// using Space Optimization
using System;

class GfG {
    static int MinCost(int[, ] cost) {
        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        // 1D dp array to store the minimum cost of the
        // current row
        int[] dp = new int[n];

        // Initialize the base cell
        dp[0] = cost[0, 0];

        // Fill the first row
        for (int j = 1; j < n; j++) {
            dp[j] = dp[j - 1] + cost[0, j];
        }

        // Fill the rest of the rows
        for (int i = 1; i < m; i++) {
          
            // Store the previous value of dp[j-1] (for
            // diagonal handling)
            int prev = dp[0];

            // Update the first column (only depends on the
            // previous row)
            dp[0] = dp[0] + cost[i, 0];

            for (int j = 1; j < n; j++) {
              
                // Store the current dp[j] before updating
                // it
                int temp = dp[j];

                // Update dp[j] using the minimum of the
                // top, left, and diagonal cells
                dp[j]
                    = cost[i, j]
                      + Math.Min(dp[j],
                                 Math.Min(dp[j - 1], prev));

                // Update prev to be the old dp[j] for the
                // diagonal calculation in the next
                // iteration
                prev = temp;
            }
        }

        // The last cell contains the minimum cost path
        return dp[n - 1];
    }

    static void Main(string[] args) {
        int[, ] cost
            = { { 1, 2, 3 }, { 4, 8, 2 }, { 1, 5, 3 } };

        Console.WriteLine(MinCost(cost));
    }
}
JavaScript
// JavaScript implementation to find the minimum cost path
// using Space Optimization
function minCost(cost) {

    const m = cost.length;
    const n = cost[0].length;

    // 1D dp array to store the minimum cost of the current
    // row
    let dp = new Array(n);

    // Initialize the base cell
    dp[0] = cost[0][0];

    // Fill the first row
    for (let j = 1; j < n; j++) {
        dp[j] = dp[j - 1] + cost[0][j];
    }

    // Fill the rest of the rows
    for (let i = 1; i < m; i++) {
    
        // Store the previous value of dp[j-1] (for diagonal
        // handling)
        let prev = dp[0];

        // Update the first column (only depends on the
        // previous row)
        dp[0] = dp[0] + cost[i][0];

        for (let j = 1; j < n; j++) {
        
            // Store the current dp[j] before updating it
            let temp = dp[j];

            // Update dp[j] using the minimum of the top,
            // left, and diagonal cells
            dp[j] = cost[i][j]
                    + Math.min(dp[j],
                               Math.min(dp[j - 1], prev));

            // Update prev to be the old dp[j] for the
            // diagonal calculation in the next iteration
            prev = temp;
        }
    }

    // The last cell contains the minimum cost path
    return dp[n - 1];
}

const cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ];
console.log(minCost(cost));

Output
8

Using Dijkstra’s Algorithm – O((m*n) * log(m*n)) Time and O(m*n) Space

The idea is to apply Dijkstra’s algorithm to find the minimum cost path from the top-left to the bottom-right corner of the grid. Dijkstra’s algorithm is well-suited for this problem since it efficiently finds the shortest path in a weighted graph, where each cell is treated as a node and each move between adjacent cells has a cost. We use a min-heap to always expand the least costly path first.

C++
// C++ implementation to find minimum cost path
// using Dijstra's Algoritms
#include <bits/stdc++.h>
using namespace std;

struct Cell {
    int x, y, cost;

    bool operator>(const Cell &other) const {
        return cost > other.cost;
    }
};

int minCost(vector<vector<int>> &cost) {
  
    int m = cost.size();
    int n = cost[0].size();

    // Directions for moving up, down, left, right, and diagonal
    vector<pair<int, int>> directions = 
    {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}};

    // Min-heap (priority queue) for Dijkstra's algorithm
    priority_queue<Cell, vector<Cell>, greater<Cell>> pq;

    // Distance matrix to store the minimum cost to reach each cell
    vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
    dist[0][0] = cost[0][0];

    pq.push({0, 0, cost[0][0]});

    // Dijkstra's algorithm
    while (!pq.empty()) {
      
        Cell curr = pq.top();
        pq.pop();

        int x = curr.x;
        int y = curr.y;

        // If we reached the bottom-right 
          // corner, return the cost
        if (x == m - 1 && y == n - 1) {
            return dist[x][y];
        }

        // Explore the neighbors
        for (auto &dir : directions) {
          
            int newX = x + dir.first;
            int newY = y + dir.second;

            // Ensure the new cell is within bounds
            if (newX >= 0 && newX < m && newY >= 0 && newY < n) {

                // Relaxation step
                if (dist[newX][newY] > dist[x][y] + cost[newX][newY]) {
                    dist[newX][newY] = dist[x][y] + cost[newX][newY];
                    pq.push({newX, newY, dist[newX][newY]});
                }
            }
        }
    }

    return dist[m - 1][n - 1];
}

int main() {
    vector<vector<int>> cost = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}};

    cout << minCost(cost) << endl;
    return 0;
}
Java
// Java implementation to find minimum cost path
// using Dijstra's Algoritms
import java.util.*;

class GfG {

    static class Cell {
        int x, y, cost;

        Cell(int x, int y, int cost) {
            this.x = x;
            this.y = y;
            this.cost = cost;
        }
    }

    static int minCost(ArrayList<ArrayList<Integer> > cost) {
        int m = cost.size();
        int n = cost.get(0).size();

        // Directions for moving up, down, left, right,
        // diagonal
        int[][] directions
            = { { -1, 0 }, { 1, 0 },   { 0, -1 },
                { 0, 1 },  { -1, -1 }, { 1, 1 } };

        // Min-heap (priority queue) for Dijkstra's
        // algorithm
        PriorityQueue<Cell> pq = new PriorityQueue<>(
            Comparator.comparingInt(a -> a.cost));

        // Distance matrix to store the minimum cost to
        // reach each cell
        int[][] dist = new int[m][n];
        for (int[] row : dist) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }
        dist[0][0] = cost.get(0).get(0);

        pq.offer(new Cell(0, 0, cost.get(0).get(0)));

        // Dijkstra's algorithm
        while (!pq.isEmpty()) {
            Cell curr = pq.poll();
            int x = curr.x;
            int y = curr.y;

            // If we reached the bottom-right corner, return
            // the cost
            if (x == m - 1 && y == n - 1) {
                return dist[x][y];
            }

            // Explore the neighbors
            for (int[] dir : directions) {
                int newX = x + dir[0];
                int newY = y + dir[1];

                // Ensure the new cell is within bounds
                if (newX >= 0 && newX < m && newY >= 0
                    && newY < n) {

                    // Relaxation step
                    if (dist[newX][newY]
                        > dist[x][y]
                              + cost.get(newX).get(newY)) {
                        dist[newX][newY]
                            = dist[x][y]
                              + cost.get(newX).get(newY);
                        pq.offer(new Cell(
                            newX, newY, dist[newX][newY]));
                    }
                }
            }
        }

        return dist[m - 1][n - 1];
    }

    public static void main(String[] args) {

        ArrayList<ArrayList<Integer> > cost
            = new ArrayList<>();
        cost.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
        cost.add(new ArrayList<>(Arrays.asList(4, 8, 2)));
        cost.add(new ArrayList<>(Arrays.asList(1, 5, 3)));

        System.out.println(minCost(cost));
    }
}
Python
# Python implementation to find minimum cost path
# using Dijstra's Algoritms
import heapq

class Cell:
    def __init__(self, x, y, cost):
        self.x = x
        self.y = y
        self.cost = cost

    def __lt__(self, other):
        return self.cost < other.cost

def min_cost(cost):
    m, n = len(cost), len(cost[0])
    
    # Directions for moving up, down, left, right, diagonal
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1),
                  (-1, -1), (1, 1)]
    
    # Min-heap for Dijkstra's algorithm
    pq = []
    
    # Distance matrix to store the minimum cost 
    # to reach each cell
    dist = [[float('inf')] * n for _ in range(m)]
    dist[0][0] = cost[0][0]
    
    heapq.heappush(pq, Cell(0, 0, cost[0][0]))
    
    # Dijkstra's algorithm
    while pq:
        curr = heapq.heappop(pq)
        x, y = curr.x, curr.y
        
        # If we reached the bottom-right corner,
        # return the cost
        if x == m - 1 and y == n - 1:
            return dist[x][y]
        
        # Explore the neighbors
        for dx, dy in directions:
            new_x, new_y = x + dx, y + dy
            
            # Ensure the new cell is within bounds
            if 0 <= new_x < m and 0 <= new_y < n:
              
                # Relaxation step
                if dist[new_x][new_y] > dist[x][y] + cost[new_x][new_y]:
                    dist[new_x][new_y] = dist[x][y] + cost[new_x][new_y]
                    
                    heapq.heappush(pq, Cell(new_x, new_y, dist[new_x][new_y]))
    
    return dist[m - 1][n - 1]

if __name__ == "__main__":
  
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]
    
    print(min_cost(cost))
C#
// C# implementation to find minimum cost path
// using Dijstra's Algoritms
using System;
using System.Collections.Generic;

class GfG {

    class Cell {
        public int x, y, cost;
        public Cell(int x, int y, int cost) {
            this.x = x;
            this.y = y;
            this.cost = cost;
        }
        
        // Implement comparison to make sure cells 
        // are sorted by cost
        public override bool Equals(object obj) {
            return obj is Cell cell &&
                   x == cell.x &&
                   y == cell.y;
        }

        public override int GetHashCode() {
            return HashCode.Combine(x, y);
        }
    }

    // Function to find the minimum cost path using Dijkstra
    static int minCost(List<List<int>> cost) {
        int m = cost.Count; 
        int n = cost[0].Count; 
        
        // Directions: Up, Down, Left, Right, Diagonal
        int[][] directions = { new int[] {-1, 0}, new int[] {1, 0},
            new int[] {0, -1}, new int[] {0, 1}, new int[] {-1, -1},
            new int[] {1, 1} };

        // Use SortedSet to simulate the priority queue
        SortedSet<Cell> pq = new SortedSet<Cell>(Comparer<Cell>.Create(
            (a, b) => a.cost != b.cost ? a.cost.CompareTo(b.cost) : 
            (a.x != b.x ? a.x.CompareTo(b.x) : a.y.CompareTo(b.y))));

        // Distance matrix to store minimum cost to each cell
        int[][] dist = new int[m][];
        for (int i = 0; i < m; i++) dist[i] = new int[n];

        // Initialize distance matrix with maximum values
        for (int i = 0; i < m; i++) 
            for (int j = 0; j < n; j++) dist[i][j] = int.MaxValue;

        // Set distance of starting point (0, 0)
        dist[0][0] = cost[0][0];

        // Add the starting cell to the priority queue
        pq.Add(new Cell(0, 0, cost[0][0]));

        // Process the queue until it's empty
        while (pq.Count > 0) {
          
            // Dequeue the cell with minimum cost
            Cell curr = pq.Min;
            pq.Remove(curr);
            int x = curr.x, y = curr.y;
            
            // If destination is reached, return the cost
            if (x == m - 1 && y == n - 1) return dist[x][y];

            // Process all valid neighbors (Up, Down, Left, Right)
            foreach (var dir in directions) {
                int newX = x + dir[0], newY = y + dir[1];
                
                // Check if the neighbor is within bounds
                if (newX >= 0 && newX < m && newY >= 0 && newY < n) {
                  
                    // If the cost to reach the neighbor is lower
                    if (dist[newX][newY] > dist[x][y] + cost[newX][newY]) {
                        dist[newX][newY] = dist[x][y] + cost[newX][newY];
                        pq.Add(new Cell(newX, newY, dist[newX][newY]));
                    }
                }
            }
        }

        // Return minimum cost to reach destination
        return dist[m - 1][n - 1];
    }

    static void Main() {

      List<List<int>> cost = new List<List<int>> {
            new List<int>{1, 2, 3},
            new List<int>{4, 8, 2},
            new List<int>{1, 5, 3}
        };

        Console.WriteLine(minCost(cost));
    }
}
JavaScript
// Javascript implementation to find minimum cost path
// using Dijstra's Algoritms

// Function to find the minimum cost path using Dijkstra
function minCost(cost) {
    let m = cost.length;
    let n = cost[0].length;

    // Directions: Up, Down, Left, Right, Diagonal
    let directions = [
        [ -1, 0 ], [ 1, 0 ], [ 0, -1 ], [ 0, 1 ],
        [ -1, -1 ], [ 1, 1 ]
    ];

    // Distance matrix to store minimum cost to each cell
    let dist = Array.from({length : m},
                          () => Array(n).fill(Infinity));

    // Set distance of starting point (0, 0)
    dist[0][0] = cost[0][0];

    // Priority queue (min-heap) using a sorted array
    let pq = [ [ 0, 0, cost[0][0] ] ];

    // Process the priority queue until it's empty
    while (pq.length > 0) {

        // Dequeue the cell with minimum cost
        pq.sort((a, b) => a[2] - b[2]);
        let [x, y, currCost] = pq.shift();

        // If destination is reached, return the cost
        if (x === m - 1 && y === n - 1)
            return dist[x][y];

        // Process all valid neighbors (Up, Down, Left,
        // Right)
        for (let dir of directions) {
            let newX = x + dir[0], newY = y + dir[1];

            // Check if the neighbor is within bounds
            if (newX >= 0 && newX < m && newY >= 0
                && newY < n) {

                // If the cost to reach the neighbor is
                // lower
                if (dist[newX][newY]
                    > currCost + cost[newX][newY]) {
                    dist[newX][newY]
                        = currCost + cost[newX][newY];
                    pq.push(
                        [ newX, newY, dist[newX][newY] ]);
                }
            }
        }
    }

    // Return minimum cost to reach destination
    return dist[m - 1][n - 1];
}

let cost = [ [ 1, 2, 3 ], [ 4, 8, 2 ], [ 1, 5, 3 ] ];

console.log(minCost(cost));

Output
8


Next Article

Similar Reads

three90RightbarBannerImg