Skip to content

Commit 70b2c74

Browse files
authored
Create dp-on-matrices.cpp
1 parent 9e95f55 commit 70b2c74

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

dp-on-matrices.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
const int N = 1003;
5+
int n, m, a[N][N], dp[N][N], vis[N][N];
6+
7+
//Returns the max sum you can achieve
8+
//when you start at (i,j) and end at (n-1, m-1)
9+
//and move only in down and right directions
10+
int go(int i, int j){
11+
if(i == n-1 and j == m-1)
12+
return a[i][j];
13+
14+
if(vis[i][j]) return dp[i][j];
15+
16+
vis[i][j] = 1;
17+
18+
int &ans = dp[i][j];
19+
20+
if(i<n-1 and j<m-1)
21+
ans = a[i][j] + max(go(i, j+1), go(i+1, j));
22+
else if(i == n-1)
23+
ans = a[i][j]+ go(i, j+1);
24+
else
25+
ans = a[i][j] + go(i+1, j);
26+
27+
return ans;
28+
}
29+
30+
int main() {
31+
int i, j;
32+
cin >> n >> m;
33+
34+
for(i = 0; i < n; i++)
35+
for(j = 0; j < m; j++)
36+
cin >> a[i][j];
37+
38+
//Display the matrix
39+
for(i = 0; i < n; i++){
40+
for(j = 0; j < m; j++)
41+
cout << a[i][j] << "\t";
42+
cout << endl;
43+
}
44+
45+
//Print the answer
46+
cout << go(0, 0) << endl;
47+
//It should be 73 i.e 1+5+9+13+14+15+16
48+
49+
50+
return 0;
51+
52+
}
53+
54+
//Input:
55+
//4 4
56+
//1 2 3 4
57+
//5 6 7 8
58+
//9 10 11 12
59+
//13 14 15 16

0 commit comments

Comments
 (0)