37. Matrix

题目描述

现在你面对一个n×m的矩阵,矩阵中的每一个元素都是一个整数,现在你需要计算从矩阵的左上角走到右下角所走过的所有元素相加的最大和。
注意:只能向右或者向下走,不能走出边界。

解答要求时间限制:1000ms, 内存限制:100MB
输入

输入第一行包含两个用空格分开的整数n (1≤ n ≤ 100)和m (1≤ m ≤ 100),表示n行m列的矩阵;接下来是n行每行包含m个用空格分开的非负的整数A (0 ≤ A ≤ 100)。

输出

输出从矩阵的左上角走到右下角所走过的所有元素相加的最大和。

样例

输入样例 1 复制

2 3
1 2 3
1 0 2

输出样例 1

8
提示样例 1
 


输入样例 2 复制

5 3
14 14 4
76 5 76
78 23 23
45 75 53
52 43 71

输出样例 2

412
提示样例 2
 


提示

Sample test1中最大和为1+2+3+2=8。

Sample test2最大和为14+76+78+45+75+53+71=412

思路:动态规划
代码:
// we have defined the necessary header files here for this problem.
// If additional header files are needed in your program, please import here.

int main()
{ 
  // please define the C++ input here. For example: int a,b; cin>>a>>b;;  
  // please finish the function body here.  
  // please define the C++ output here. For example:cout<<____<<endl; 
  
   int matrix[105][105];
    int M,N;
    cin>>M>>N;
    for(int i =0 ;i<M;i++)
    {
        for(int j = 0;j<N;j++)
        {
            cin>>matrix[i][j];
        }
    }
    int dp[105][105];
    for(int i = 0;i<M;i++)
    {
        dp[i][0] = matrix[i][0];
    }
        for(int j = 0;j<M;j++)
    {
        dp[0][j] = matrix[0][j];
    }
    for(int i = 0;i<M;i++)
    {
        for(int j = 0;j<N;j++)
        {
            dp[i][j]=max(dp[i-1][j],dp[i][j-1])+matrix[i][j];
        }
    }
    cout<<dp[M-1][N-1]<<endl;
   return 0;
}

 

posted @ 2021-10-27 20:08  A-inspire  Views(221)  Comments(0Edit  收藏  举报