捡苹果问题,具体的问题描述请见动态规划:从新手到专家中的中级部分。
在矩阵中,分布着一些苹果。在矩阵中,一个人只能向下或者向右,请问它所能捡到的最大个数的苹果是多少。以下矩阵初始化中,虽然是只能0,1个数,但其实其他任意整数也是可以的。
appleNumbers[rowIndex][colIndex] = appleMatrix[rowIndex][colIndex]+max(appleNumbers[rowIndex][colIndex-1] ,appleNumbers[rowIndex-1][colIndex]);
以下是具体代码
#include <stdio.h>
#define NumRow 4
#define NumCol 5
int max(int a,int b)
{
return (a > b) ? a : b;
}
int PickApple(int appleMatrix[NumRow][NumCol])
{
int rowIndex, colIndex;
int appleNumbers[NumRow][NumCol];
//初始化矩阵 appleNumbers的第0行和第0列
appleNumbers[0][0] = appleMatrix[0][0];
for (rowIndex=1;rowIndex<NumRow;rowIndex++)
{
appleNumbers[rowIndex][0] = appleNumbers[rowIndex-1][0]+appleMatrix[rowIndex][0];
}
for (colIndex=1;colIndex<NumCol;colIndex++)
{
appleNumbers[0][colIndex] = appleNumbers[0][colIndex-1]+appleMatrix[0][colIndex];
}
//开始捡苹果
for (rowIndex=1;rowIndex<NumRow;rowIndex++)
{
for (colIndex=1;colIndex<NumCol;colIndex++)
{
appleNumbers[rowIndex][colIndex] = appleMatrix[rowIndex][colIndex]+max(appleNumbers[rowIndex][colIndex-1] ,appleNumbers[rowIndex-1][colIndex]);
}
}
printf("In the matrix, At most pick %d apples. \n", appleNumbers[rowIndex-1][colIndex-1]);
return 0;
}
int main()
{
int appleMatrix[NumRow][NumCol] =
{ {1,0,1,1,0}, {0,1,1,0,1}, {1,0,1,0,0}, {0,0,1,1,1}};
PickApple(appleMatrix);
getchar();
return 0;
}