Min Cost Path in Grid with Right, Down and Diagonal Moves

Last Updated : 17 Oct, 2026

Given a matrix cost[][] of size n x m. Each cell contains a value that represents the cost to move through that cell.

  • You start at the top-left cell (0,0) and must reach the bottom-right cell (n-1, m-1).
  • From any cell (i, j), you can move to (i, j+1), (i+1, j), or (i+1, j+1).

Find the minimum cost required to reach the bottom-right corner. The cost of a path is the sum of all values on the path including both the start and end cells.

Examples:

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

2056958719

Output: 8
Explanation: One minimum-cost path is (0,0) -> (0,1) -> (1,2) -> (2,2), with total cost 1 + 2 + 2 + 3 = 8.

2056958720

Input: cost[][] = [[5, 6], [7, 2]]

2056958717

Output: 7
Explanation: The minimum-cost path is (0,0) -> (1,1), with total cost 5 + 2 = 7.

2056958718
Try It Yourself
redirect icon

[Naive Approach] Recursion - O(3 ^ (m * n)) Time and O(1) Space

In this problem, we need to move from the starting cell (0,0) to the last cell (m-1, n-1). From every cell, we have three choices: we can move down (i+1, j), right (i, j+1), or diagonally (i+1, j+1). Whenever a problem gives multiple choices at every step, the first natural approach that comes to mind is recursion, because recursion allows us to break the problem into smaller independent subproblems.

To solve this using recursion, we start from the starting cell (0,0) and at each step we try all three possible moves.

  • Each recursive call represents taking one of the paths, and since we want the minimum cost path, we simply try all possibilities and take the minimum among them.
  • The base case occurs when the recursion reaches the last cell (m-1, n-1) - at that point, we stop and return the cost of that cell because the destination is reached.
C++
#include <iostream>
#include<vector>
using namespace std;

// Function to return the cost of the minimum cost path
int findMinCost(vector<vector<int>>& cost, int x, int y) {
    int m = cost.size();
    int n = cost[0].size();
  
    // If indices are out of bounds, return a large value
    if (x >= m || y >= n) {
        return INT_MAX;
    }

    // Base case: bottom cell
    if (x == m - 1 && y == n - 1) {
        return cost[x][y];
    }

    // Recursively calculate minimum cost from 
    // all possible paths
    int right = findMinCost(cost, x, y + 1);
    int down = findMinCost(cost, x + 1, y);
    int diag = findMinCost(cost, x + 1, y + 1);

    int best = min(right, min(down, diag));

    return cost[x][y] + best;
   
}

// function to find the minimum cost path
// to reach (m - 1, n - 1) from (0, 0)
int minCost(vector<vector<int>>& cost) {
    return findMinCost(cost, 0, 0);
}

int main() {
  
    vector<vector<int>> cost = {
        { 1, 2, 3 },
        { 4, 8, 2 },
        { 1, 5, 3 } 
    };
    cout << minCost(cost);
    return 0;
}
Java
import java.util.Arrays;

public class GFG {

    // Function to return the cost of the minimum cost path
    static int findMinCost(int[][] cost, int x, int y) {
        int m = cost.length;
        int n = cost[0].length;

        // If indices are out of bounds, return a large value
        if (x >= m || y >= n) return Integer.MAX_VALUE;

        // Base case: bottom cell
        if (x == m - 1 && y == n - 1) return cost[x][y];

        // Recursively calculate minimum cost from all possible paths
        int right = findMinCost(cost, x, y + 1);
        int down = findMinCost(cost, x + 1, y);
        int diag = findMinCost(cost, x + 1, y + 1);

        int best = Math.min(right, Math.min(down, diag));

        return cost[x][y] + best;
    }

    // Function to find the minimum cost path
    // to reach (m - 1, n - 1) from (0, 0)
    static int minCost(int[][] cost) {
        return findMinCost(cost, 0, 0);
    }

    public static void main(String[] args) {
        int[][] cost = {
            {1, 2, 3},
            {4, 8, 2},
            {1, 5, 3}
        };
        System.out.println(minCost(cost));
    }
}
Python
import sys

# Function to return the cost of the minimum cost path
def findMinCost(cost, x, y):
    m = len(cost)
    n = len(cost[0])

    # If indices are out of bounds, return a large value
    if x >= m or y >= n:
        return sys.maxsize

    # Base case: bottom cell
    if x == m - 1 and y == n - 1:
        return cost[x][y]

    # Recursively calculate minimum cost from all possible paths
    right = findMinCost(cost, x, y + 1)
    down = findMinCost(cost, x + 1, y)
    diag = findMinCost(cost, x + 1, y + 1)

    best = min(right, down, diag)

    return cost[x][y] + best

# Function to find the minimum cost path
# to reach (m - 1, n - 1) from (0, 0)
def minCost(cost):
    return findMinCost(cost, 0, 0)



if __name__ == "__main__":
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]
    print(minCost(cost))
C#
using System;

class GFG {

    // Function to return the cost of the minimum cost path
    static int findMinCost(int[,] cost, int x, int y) {
        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        // If indices are out of bounds, return a large value
        if (x >= m || y >= n) return int.MaxValue;

        // Base case: bottom cell
        if (x == m - 1 && y == n - 1) return cost[x, y];

        // Recursively calculate minimum cost from all possible paths
        int right = findMinCost(cost, x, y + 1);
        int down = findMinCost(cost, x + 1, y);
        int diag = findMinCost(cost, x + 1, y + 1);

        int best = Math.Min(right, Math.Min(down, diag));

        return cost[x, y] + best;
    }

    // Function to find the minimum cost path
    // to reach (m - 1, n - 1) from (0, 0)
    static int minCost(int[,] cost) {
        return findMinCost(cost, 0, 0);
    }

    static void Main() {
        int[,] cost = {
            {1, 2, 3},
            {4, 8, 2},
            {1, 5, 3}
        };
        Console.WriteLine(minCost(cost));
    }
}
JavaScript
// Function to return the cost of the minimum cost path
function findMinCost(cost, x, y) {
    let m = cost.length;
    let n = cost[0].length;

    // If indices are out of bounds, return a large value
    if (x >= m || y >= n) {
        return Number.MAX_SAFE_INTEGER;
    }

    // Base case: bottom-right cell
    if (x === m - 1 && y === n - 1) {
        return cost[x][y];
    }

    // Recursively calculate minimum cost for right, down and diagonal
    let right = findMinCost(cost, x, y + 1);
    let down = findMinCost(cost, x + 1, y);
    let diag = findMinCost(cost, x + 1, y + 1);

    // Find the minimum among the three paths
    let best = right;
    if (down < best) best = down;
    if (diag < best) best = diag;

    return cost[x][y] + best;
}

// Function to find the minimum cost path
// to reach (m - 1, n - 1) from (0, 0)
function minCost(cost) {
    return findMinCost(cost, 0, 0);
}

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

console.log(minCost(cost)); 

Output
8

[Better Approach - 1] Dijkstra's Algorithm - O((m * n) * log(m * n)) Time and O(m * n) Space

The idea is to apply Dijskra's Algorithm to find the minimum cost path from the top-left to the bottom-right corner of the grid. 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++
#include <iostream>
using namespace std;

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

    vector<pair<int, int>> directions = 
    {{1, 0}, {0, 1}, {1, 1}};

    // Min-heap (priority queue) for Dijkstra's algorithm
    priority_queue<vector<int>, 
    vector<vector<int>>, greater<vector<int>>> 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({cost[0][0], 0, 0});

    while (!pq.empty()) {
      
        vector<int> curr = pq.top();
        pq.pop();

        int x = curr[1];
        int y = curr[2];

        // 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 < m && 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({dist[newX][newY], 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);
    return 0;
}
Java
import java.util.Arrays;
import java.util.PriorityQueue;

public class GFG {

    public static int minCost(int[][] cost) {

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

        int[][] directions = {{1,0}, {0,1}, {1,1}};

        // Min-heap (priority queue) for Dijkstra's algorithm
        PriorityQueue<int[]> pq = new PriorityQueue<>(
                (a, b) -> Integer.compare(a[0], b[0])
        );

        // 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[0][0];

        pq.add(new int[]{cost[0][0], 0, 0});

        while (!pq.isEmpty()) {

            int[] curr = pq.poll();
            int x = curr[1];
            int y = curr[2];

            // 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 < m && newY < n) {

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

        return dist[m - 1][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
import heapq
import sys

def minCost(cost):

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

    directions = [(1, 0), (0, 1), (1, 1)]

    # Min-heap (priority queue) for Dijkstra's algorithm
    pq = []

    # Distance matrix to store the minimum cost to reach each cell
    dist = [[sys.maxsize] * n for _ in range(m)]
    dist[0][0] = cost[0][0]

    heapq.heappush(pq, (cost[0][0], 0, 0))

    while pq:

        currCost, x, y = heapq.heappop(pq)

        # If we reached the bottom-right corner, return the cost
        if x == m - 1 and y == n - 1:
            return dist[x][y]

        # Explore neighbors
        for dx, dy in directions:

            newX = x + dx
            newY = y + dy

            # Ensure the new cell is within bounds
            if newX < m and newY < n:

                # Relaxation step
                if dist[newX][newY] > dist[x][y] + cost[newX][newY]:
                    dist[newX][newY] = dist[x][y] + cost[newX][newY]
                    heapq.heappush(pq, (dist[newX][newY], newX, newY))

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


if __name__ == "__main__":
    cost = [
        [1,2,3],
        [4,8,2],
        [1,5,3]
    ]
    
    print(minCost(cost))
C#
using System;
using System.Collections.Generic;

class GFG {

    public static int minCost(int[,] cost) {

        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        int[][] directions = new int[][] {
            new int[] {1,0},
            new int[] {0,1},
            new int[] {1,1}
        };

        // Min-heap (priority queue) for Dijkstra's algorithm
        var pq = new PriorityQueue<(int, int, int), int>();

        // Distance matrix to store the minimum cost to reach each cell
        int[,] dist = new int[m, n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++)
                dist[i, j] = int.MaxValue;
        }
        dist[0, 0] = cost[0, 0];

        pq.Enqueue((cost[0, 0], 0, 0), cost[0, 0]);

        while (pq.Count > 0) {

            var curr = pq.Dequeue();
            int x = curr.Item2;
            int y = curr.Item3;

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

            // Explore neighbors
            foreach (var dir in directions) {

                int newX = x + dir[0];
                int newY = y + dir[1];

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

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

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

    static void Main() {

        int[,] cost = {
            {1,2,3},
            {4,8,2},
            {1,5,3}
        };

        Console.WriteLine(minCost(cost));
    }
}
JavaScript
function minCost(cost)
{

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

    const directions = [ [ 1, 0 ], [ 0, 1 ], [ 1, 1 ] ];

    // Min-heap (priority queue) for Dijkstra's algorithm
    const pq = [ [ cost[0][0], 0, 0 ] ];

    // Distance matrix to store the minimum
    //  cost to reach each cell
    const dist = Array.from(
        {length : m},
        () => Array(n).fill(Number.MAX_SAFE_INTEGER));
    dist[0][0] = cost[0][0];

    pq.sort((a, b) => a[0] - b[0]);

    while (pq.length > 0) {

        const curr = pq.shift();
        const x = curr[1];
        const y = curr[2];

        // 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 (const dir of directions) {

            const newX = x + dir[0];
            const newY = y + dir[1];

            // Ensure the new cell is within bounds
            if (newX < m && 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(
                        [ dist[newX][newY], newX, newY ]);
                    pq.sort((a, b) => a[0] - b[0]);
                }
            }
        }
    }
    return dist[m - 1][n - 1];
}

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

Output
8

[Better Approach - 2] Top-Down DP (Memoization) - O(m * n) Time and O(m * n) Space

minCost

If we look at the recursion tree, we notice that in recursion approach, many subproblems are solved again and again, which increases the time complexity. To handle this, we use a DP (memoization) approach. The idea is to store previously computed results in a DP table.

We create a 2D DP table of size (m × n) because there are two parameters that change in the recursive approach. After computing a subproblem, we store the result in the table. Later, when we encounter the same subproblem again, we check the table first. If the result is already computed, we return it instead of solving it again.

C++
#include <iostream>
#include<vector>
using namespace std;

// Function to return the cost of the minimum cost path
int findMinCost(vector<vector<int>>& cost, int x, 
                int y, vector<vector<int>> &dp) {
    int m = cost.size();
    int n = cost[0].size();
  
    // If indices are out of bounds, return a large value
    if (x >= m || y >= n) {
        return INT_MAX;
    }

    // Base case: bottom cell
    if (x == m - 1 && y == n - 1) {
        return cost[x][y];
    }

    // Check if the result is already computed
    if (dp[x][y] != -1) {
        return dp[x][y];
    }

    int right = findMinCost(cost, x, y + 1,dp);
    int down = findMinCost(cost, x + 1, y,dp);
    int diag = findMinCost(cost, x + 1, y + 1,dp);

    int best = min(right, min(down, diag));

    return dp[x][y]= cost[x][y] + best;
}

// function to find the minimum cost path
// to reach (m - 1, n - 1) from (0, 0)
int minCost(vector<vector<int>>& cost) {
    int m = cost.size();
    int n = cost[0].size();

    // create 2d array to store the minimum cost path
    vector<vector<int>> dp(m, vector<int>(n, -1));
    
    return findMinCost(cost, 0, 0, dp);
}

int main() {
    vector<vector<int>> cost = {
        { 1, 2, 3 },
        { 4, 8, 2 },
        { 1, 5, 3 } 
    };
    cout << minCost(cost);
    return 0;
}
Java
import java.util.Arrays;

public class GFG {

    // Function to return the cost of the minimum cost path
    static int findMinCost(int[][] cost, int x, int y, int[][] dp) {
        int m = cost.length;
        int n = cost[0].length;

        // If indices are out of bounds, return a large value
        if (x >= m || y >= n) return Integer.MAX_VALUE;

        // Base case: bottom cell
        if (x == m - 1 && y == n - 1) return cost[x][y];

        // Check if the result is already computed
        if (dp[x][y] != -1) return dp[x][y];

        int right = findMinCost(cost, x, y + 1, dp);
        int down = findMinCost(cost, x + 1, y, dp);
        int diag = findMinCost(cost, x + 1, y + 1, dp);

        int best = Math.min(right, Math.min(down, diag));

        return dp[x][y] = cost[x][y] + best;
    }

    // function to find the minimum cost path
    // to reach (m - 1, n - 1) from (0, 0)
    static int minCost(int[][] cost) {
        int m = cost.length;
        int n = cost[0].length;

        // create 2d array to store the minimum cost path
        int[][] dp = new int[m][n];
        for (int[] row : dp) Arrays.fill(row, -1);

        return findMinCost(cost, 0, 0, dp);
    }

    public static void main(String[] args) {
        int[][] cost = {
            { 1, 2, 3 },
            { 4, 8, 2 },
            { 1, 5, 3 }
        };
        System.out.println(minCost(cost));
    }
}
Python
import sys

# Function to return the cost of the minimum cost path
def findMinCost(cost, x, y, dp):
    m = len(cost)
    n = len(cost[0])

    # If indices are out of bounds, return a large value
    if x >= m or y >= n:
        return sys.maxsize

    # Base case: bottom cell
    if x == m - 1 and y == n - 1:
        return cost[x][y]

    # Check if the result is already computed
    if dp[x][y] != -1:
        return dp[x][y]

    right = findMinCost(cost, x, y + 1, dp)
    down = findMinCost(cost, x + 1, y, dp)
    diag = findMinCost(cost, x + 1, y + 1, dp)

    best = min(right, down, diag)

    dp[x][y] = cost[x][y] + best
    return dp[x][y]


# function to find the minimum cost path
# to reach (m - 1, n - 1) from (0, 0)
def minCost(cost):
    m = len(cost)
    n = len(cost[0])

    # create 2d array to store the minimum cost path
    dp = [[-1]*n for _ in range(m)]
    return findMinCost(cost, 0, 0, dp)


if __name__ == "__main__":
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]
    print(minCost(cost))
C#
using System;

class GFG
{
    // Function to return the cost of the minimum cost path
    static int findMinCost(int[,] cost, int x, int y, int[,] dp)
    {
        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        // If indices are out of bounds, return a large value
        if (x >= m || y >= n) return int.MaxValue;

        // Base case: bottom cell
        if (x == m - 1 && y == n - 1) return cost[x, y];

        // Check if the result is already computed
        if (dp[x, y] != -1) return dp[x, y];

        int right = findMinCost(cost, x, y + 1, dp);
        int down = findMinCost(cost, x + 1, y, dp);
        int diag = findMinCost(cost, x + 1, y + 1, dp);

        int best = Math.Min(right, Math.Min(down, diag));

        return dp[x, y] = cost[x, y] + best;
    }

    // function to find the minimum cost path
    // to reach (m - 1, n - 1) from (0, 0)
    static int minCost(int[,] cost)
    {
        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        // create 2d array to store the minimum cost path
        int[,] dp = new int[m, n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                dp[i, j] = -1;

        return findMinCost(cost, 0, 0, dp);
    }

    static void Main()
    {
        int[,] cost = {
            { 1, 2, 3 },
            { 4, 8, 2 },
            { 1, 5, 3 }
        };
        Console.WriteLine(minCost(cost));
    }
}
JavaScript
// Function to return the cost of the minimum cost path
function findMinCost(cost, x, y, dp) {
    const m = cost.length;
    const n = cost[0].length;

    // If indices are out of bounds, return a large value
    if (x >= m || y >= n) return Number.MAX_SAFE_INTEGER;

    // Base case: bottom cell
    if (x === m - 1 && y === n - 1) return cost[x][y];

    // Check if the result is already computed
    if (dp[x][y] !== -1) return dp[x][y];

    const right = findMinCost(cost, x, y + 1, dp);
    const down = findMinCost(cost, x + 1, y, dp);
    const diag = findMinCost(cost, x + 1, y + 1, dp);

    const best = Math.min(right, down, diag);

    dp[x][y] = cost[x][y] + best;
    return dp[x][y];
}

// function to find the minimum cost path
// to reach (m - 1, n - 1) from (0, 0)
function minCost(cost) {
    const m = cost.length;
    const n = cost[0].length;

    // create 2d array to store the minimum cost path
    const dp = Array.from({ length: m }, () => Array(n).fill(-1));

    return findMinCost(cost, 0, 0, dp);
}

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

Output
8

[Better Approach - 3] Bottom-Up DP (Tabulation) - O(m * n) Time and O(m * n) Space

In the previous approach, we used recursion along with memoization. Even though memoization helps us avoid recomputing the same subproblems, the recursive structure still makes the solution slower and harder to manage for large inputs. To make the solution more efficient, we switch to a bottom-up dynamic programming method, where we build the answer iteratively.

The idea is simple: we directly fill a DP table step by step. First, we set the base case:

  • dp[0][0] = cost[0][0], because the starting cell’s minimum cost is just its own value.
  • First row: Since movement is only from the left,
    dp[0][j] = dp[0][j - 1] + cost[0][j] (for j > 0)
  • First column: Since movement is only from above,
    dp[i][0] = dp[i - 1][0] + cost[i][0] (for i > 0)

Once these base cases are set, the remaining table can be filled using the main DP relation. For every cell (i, j), we consider the minimum cost among the three possible ways to reach it and add the current cell’s cost to that minimum. By filling the table in this order, we ensure that all required subproblems are already solved when we need them.

C++
#include <iostream>
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);
    return 0;
}
Java
class GFG {

    static int minCost(int[][] cost)
    {

        int m = cost.length;
        int n = cost[0].length;
        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]));
            }
        }

        return dp[m - 1][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
from typing import List
import sys

def minCost(cost: List[List[int]]) -> int:
    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])
    
    return dp[m - 1][n - 1]

if __name__ == "__main__":
    cost = [
        [1, 2, 3],
        [4, 8, 2],
        [1, 5, 3]
    ]
    print(minCost(cost))
C#
using System;

class GFG {

    static int minCost(int[, ] cost)
    {

        int m = cost.GetLength(0);
        int n = cost.GetLength(1);

        int[, ] dp = new int[m, n];

        // Base cell
        dp[0, 0] = cost[0, 0];

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

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

        // Fill the rest of the 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]));
            }
        }

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

    static void Main()
    {

        int[, ] cost
            = { { 1, 2, 3 }, { 4, 8, 2 }, { 1, 5, 3 } };

        Console.WriteLine(minCost(cost));
    }
}
JavaScript
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];
}

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

Output
8

[Expected Approach] 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++
#include <iostream>
#include<vector>
using namespace std;

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

    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++) {
        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++) {
            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});
            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
class GFG {

    static int minCost(int[][] cost) {

        int m = cost.length;
        int n = cost[0].length;
        int[] dp = new int[n];

        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++) {
            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++) {
                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));
                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
def minCost(cost):

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

    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):
        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):
            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)
            prev = temp

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


if __name__ == "__main__":
    cost = [[1,2,3],[4,8,2],[1,5,3]]
    print(minCost(cost))
C#
using System;

class GFG {

    static int minCost(int[,] cost) {

        int m = cost.GetLength(0);
        int n = cost.GetLength(1);
        int[] dp = new int[n];

        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++) {
            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++) {
                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));
                prev = temp;
            }
        }

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

    static void Main() {

        int[,] cost = {
            {1,2,3},
            {4,8,2},
            {1,5,3}
        };

        Console.WriteLine(minCost(cost));
    }
}
JavaScript
function minCost(cost) {

    let m = cost.length;
    let n = cost[0].length;
    let dp = new Array(n).fill(0);

    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++) {
        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++) {
            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], dp[j - 1], prev);
            prev = temp;
        }
    }

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

//Driver Code
let cost = [[1,2,3],[4,8,2],[1,5,3]];
console.log(minCost(cost));

Output
8
Comment