Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Create MinCostPath.cpp
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You 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. You may assume that all costs are positive integers.
  • Loading branch information
sanjaymajhi authored Oct 3, 2020
commit 4698b931bb471f09409dadaadb9a7686ad638716
39 changes: 39 additions & 0 deletions Algorithms/Dynamic Programming/C++/MinCostPath.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;

const int row = 3;
const int col = 3;

int minCost(int cost[row][col]) {

// for 1st column
for (int i=1 ; i<row ; i++){
cost[i][0] += cost[i-1][0];
}

// for 1st row
for (int j=1 ; j<col ; j++){
cost[0][j] += cost[0][j-1];
}

// for rest of the 2d matrix
for (int i=1 ; i<row ; i++) {
for (int j=1 ; j<col ; j++) {
cost[i][j] += min(cost[i-1][j-1], min(cost[i-1][j], cost[i][j-1]));
}
}

// returning the value in last cell
return cost[row-1][col-1];
}
int main(int argc, char const *argv[])
{
int cost[row][col] = { {1, 2, 3},
{4, 8, 2},
{1, 5, 3} };

cout << minCost(cost) << endl;
return 0;
}