给定m*n的矩阵,每个位置是一个非负整数,从左上角开始,每次只能朝右和下走,走到右下角,但只走一次,求总和最小的路径。
#define N 4
int dp[2][N];
bool isVaild(int step, int x, int n) {
if (x >= 0 && x < n && step - x >= 0 && step - x < n) {
return true;
}
return false;
}
//获取上一状态的值
int getLastNum(int step, int x, int n) {
return isVaild(step, x, n) ? dp[step % 2][x] : INT_MAX;
}
int findCellMin(int matrix[][N], int n) {
//第0步初始化值
for (int i = 0; i < n; ++i) {
dp[0][i] = INT_MAX;
}
//原点状态
dp[0][0] = matrix[0][0];
//最终步数
int endStep = 2 * n - 2;
for (int step = 1; step <= endStep; ++step) {
int cur = step % 2;
for (int j = 0; j < n; ++j) {
dp[cur][j] = INT_MAX;
if (!isVaild(step, j, n)) {
continue;
}
dp[cur][j] = min(dp[cur][j], getLastNum(step - 1, j - 1, n));
dp[cur][j] = min(dp[cur][j], getLastNum(step - 1, j, n));
dp[cur][j] += matrix[j][step - j];
}
}
return dp[endStep % 2][n - 1];
}