1. 题目
2. 解答
data[i][j]表示位置i,j的值
dp[i][j]表示i,j位置的路径最小值;
0. 如果i = 0, j = 0, dp[i][j] = data[i][j];
- 如果i = 0,j != 0,dp[i][j] = data[i][j] + dp[i][j -1];
- 如果i!= 0, j = 0,dp[i][j] = data[i][j] + dp[i -1][j];
- 其他情况:dp[i][j] = data[i][j] + min(dp[i-1][j], dp[i][j - 1])
#include <stdio.h>
#include <stdlib.h>
int min(int a, int b)
{
return a < b? a:b;
}
int solve(int **data, int m, int n)
{
int dp[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
dp[i][j] = data[i][j];
} else if (i == 0 && j!= 0) {
dp[i][j] = data[i][j] + dp[i][j -1];
} else if (i != 0 && j == 0) {
dp[i][j] = data[i][j] + dp[i -1][j];
} else {
dp[i][j] = data[i][j] + min(dp[i][j -1], dp[i -1][j]);
}
}
}
return dp[m-1][n-1];
}
int main()
{
int m,n;
scanf("%d %d", &m, &n);
int **data = malloc(sizeof(int *)*m);
for (int i = 0; i < m; i++) {
data[i] = malloc(sizeof(int)*n);
for (int j = 0; j < n; j++)
scanf("%d", &data[i][j]);
}
int result = solve(data, m, n);
printf("result:%d\n", result);
return 0;
}
运行:
G3-3579:~/data/source/leetcode$ gcc 64smallpath.c
G3-3579:~/data/source/leetcode$ ./a.out
3 3
1 3 1
1 5 1
4 2 1
result:7
G3-3579:~/data/source/leetcode$ ./a.out
2 3
1 2 3
4 5 6
result:12