Descriptive narrative of the problem
There are n*m on the plane, and a certain number of apples are placed in each lattice. You start at the upper left corner of the grid, each step can just go down or to the right, every time you go to a grid to collect the apples in the lattice, so down, you can collect the maximum number of apples.
Input:
Enter the number of rows and columns in the first row
Then enter the number of apples in each grid row by line
Output:
The maximum number of apples that can be received.
Thinking analysis
This is a typical two-dimensional array dp problem
Basic Status:
The number of apples collected is dp[x][y] when you reach the grid in column y of line X.
Transfer equation:
Because you can only walk to the right or down, so when you get to the grid in row y of line x, you may have arrived at the grid from row x-1 or column x y-1, and we will only collect the most apple option.
So:
Dp[x][y] = max (if (x>0) dp[x-1][y], if (y>0) dp[x][y-1])
Writing code
Show you code:
#include <iostream> #include <string.h>using namespace Std;int a[100][100];int dp[100][100];int m,n;void DP _fun (int x,int y) {dp[x][y] = A[x][y];int max = 0;if (x > 0 && Max < dp[x-1][y]) {max = dp[x-1][y];} if (Y > 0 && Max < dp[x][y-1]) {max = dp[x][y-1];} Dp[x][y] + = max;if (x<m-1) {dp_fun (x+1,y);} if (y<n-1) {dp_fun (x,y+1);} return;} int main () {memset (dp,0,sizeof (DP)); cin>>m>>n;for (int i=0;i<m;i++) {for (int j=0;j<n;j++) {cin> >A[I][J];}} Dp_fun (0,0); for (int. i=0;i<m;i++) {for (int j=0;j<n;j++) {cout<<dp[i][j]<< "\ T";} Cout<<endl;} return 0;}
Demo Sample data: