动态规划示例四

来源:互联网 发布:无损鉴别软件 编辑:程序博客网 时间:2024/06/04 18:10

捡苹果问题,具体的问题描述请见动态规划:从新手到专家中的中级部分。

在矩阵中,分布着一些苹果。在矩阵中,一个人只能向下或者向右,请问它所能捡到的最大个数的苹果是多少。以下矩阵初始化中,虽然是只能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 5int 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;}

0 0
原创粉丝点击