I am trying to solve this problem through dynamic programming:
You are given a matrix of n rows and m columns. Every element has a number and the rabbit staying at the top left element.
Calculate the maximum sum such that the rabbit gets to the bottom element and only two moved allowed:
Two steps right and 1 step down (x+2, y+1);
Two steps down and 1 step to the right (x+1, y+2);Input:
The first line contains two naturals n and m (1 ≤ n, m ≤ 103) – the quantity of rows and columns of the matrix.
The next n lines contain m numbers – the values of the matrix elements.
The top left coordinates are (1, 1), the bottom right corner’s – (n, m).
Output:
The maximum sum so that the rabbit reaches the bottom right. If bottom right can not be reached, output
-
Input 1:
3 3 5 0 0 0 1 2 1 0 1
Output 1:
-
Input 2:
4 4 5 2 1 0 1 0 0 0 2 1 3 0 0 0 1 7
Output 2:
13
This the code I tried to develop:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
using namespace std;
void findMaxSum(int *a[], int r, int c)
{
int **res = new int*[r];
for (int i = 0; i < r; i++) {
res[i] = new int[c];
for (int j = 0; j < c; j++)
res[i][j] = -1;
}
for (int i = 0; i < r-1; i++) {
for (int j = i; j < c-1; j++) {
res[i + 1][j + 2] = max(a[i][j] + a[i + 1][j + 2], res[i + 1][j + 2]);
res[i + 2][j + 1] = max(a[i][j] + a[i + 2][j + 1], res[i + 2][j + 1]);
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
cout << res[i][j] << " ";
cout << endl;
}
delete[] res;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int r, c;
cin >> r >> c;
int **a = new int*[r];
for (int i = 0; i < r; i++) {
a[i] = new int[c];
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
cin >> a[i][j];
}
findMaxSum(a, r, c);
delete[] a;
return 0;
}
Is this the approach, are the calculations inside for loops correct?