题解 | #矩阵的最小路径和#
矩阵的最小路径和
https://www.nowcoder.com/practice/38ae72379d42471db1c537914b06d48e
#include <iostream> using namespace std; const int N = 510; int a[N][N]; int f[N][N]; int main() { int n, m; cin >> n >> m; for(int i = 1; i <= n; i ++) for(int j = 1; j <= m; j ++) cin >> a[i][j]; // 初始化第一列 只能从上方到达 for(int i = 1; i <= n; i ++) { f[i][1] = f[i - 1][1] + a[i][1]; } for(int j = 1; j <= m; j ++) { f[1][j] = f[1][j - 1] + a[1][j]; } for(int i = 2; i <= n; i ++) for(int j = 2; j <= m; j ++) { f[i][j] = min(f[i - 1][j] + a[i][j], f[i][j - 1] + a[i][j]); } cout << f[n][m] << endl; }