• 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;
    }
    以大多数人努力程度之低,根本轮不到去拼天赋~
  • 相关阅读:
    设计模式>经典设计模式一览 小强斋
    java基础>Java Collections Framework 小强斋
    如何查看python中包的版本
    gcc安装包下载地址
    Linux下boost库的编译及安装
    centos中如何自动获取IP、获取网关
    src/delly.h:8:10: fatal error: boost/graph/adjacency_list.hpp: No such file or directory
    linux系统中如何查看本机IP
    分布式事务解决方案
    Java常用的并发类总结列表
  • 原文地址:https://www.cnblogs.com/gcter/p/15472722.html
Copyright © 2020-2023  润新知