Skip to content

Commit 5d42856

Browse files
Add minimum cost path problem
1 parent 3c9a591 commit 5d42856

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.Scanner;
2+
3+
public class MinCostPath {
4+
5+
public static int minCostPathDP(int arr[][],int row, int column) {
6+
int m = row;
7+
int n = column;
8+
int storage[][] = new int[m][n];
9+
storage[m - 1][n - 1] = arr[m - 1][n - 1];
10+
// Last Row
11+
for (int j = n - 2; j >= 0; j--) {
12+
storage[m - 1][j] = storage[m - 1][j + 1] + arr[m - 1][j];
13+
}
14+
// Last Column
15+
for (int i = m - 2; i >= 0; i--) {
16+
storage[i][n - 1] = storage[i + 1][n - 1] + arr[i][n - 1];
17+
}
18+
for (int i = m - 2; i >= 0; i--) {
19+
for (int j = n - 2; j >= 0; j--) {
20+
storage[i][j] = arr[i][j]
21+
+ Math.min(storage[i][j + 1], Math.min(
22+
storage[i + 1][j + 1], storage[i + 1][j]));
23+
}
24+
}
25+
return storage[0][0]+arr[row][column];
26+
}
27+
public static void main(String args[]) {
28+
Scanner s = new Scanner(System.in);
29+
int rows = s.nextInt();
30+
int columns = s.nextInt();
31+
int arr[][] = new int[rows][columns];
32+
for (int i = 0; i < rows; i++) {
33+
for (int j = 0; j < columns; j++) {
34+
arr[i][j] = s.nextInt();
35+
}
36+
}
37+
int row = s.nextInt();
38+
int column = s.nextInt();
39+
System.out.println(minCostPathDP(arr,row,column));
40+
s.close();
41+
}
42+
}
43+

0 commit comments

Comments
 (0)