题解 | #矩阵的最小路径和#

矩阵的最小路径和

https://www.nowcoder.com/practice/38ae72379d42471db1c537914b06d48e

#include <iostream>
#include <cstring>
using namespace std;
const int N = 501;
int map[N][N];
int dp[N][N]; //其中 dp[i][j]表示  到位置(i,j)时的最小路径和

int main() {

    int n, m;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            dp[i][j] = 500000;
        }
    }
    //cout << "tet = " << dp[0][1] << endl;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            scanf("%d", &map[i][j]);
        }
    }
    //cout << "n= " << n << " m= " << m << endl;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            if (i == 1 && j == 1) {
                dp[i][j] = map[i][j];
                continue;
            }
            //从哪里来
            dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + map[i][j];
            //cout << "i=" << i << " j= " << j << " dp[i][j]= " << dp[i][j] << endl;
        }

    printf("%d", dp[n][m]);

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

挣K存W养DOG:他真的很中意你,为什么不回他
点赞 评论 收藏
分享
11-04 14:10
东南大学 Java
_可乐多加冰_:去市公司包卖卡的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务