给定一个数字矩阵,试找出一条从左上角到右下角的一条路径,要求路径上的数字和最小。
思路一:
使用动态规划思想,用当前路径最小数字和替换原来位置上的数据,直至到达右下角
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
using namespace std;
#define min(x,y) (x<y?x:y)
int main()
{
int data[3][5] = { { 1, 4, 8, 2, 9 }, { 1, 4, 6, 7, 8 }, { 1, 1, 1, 1, 1 } };
for (int i = 0; i<3;i++)
for (int j = 0; j<5;j++)
{
if (i == 0 && j == 0)
continue;
else if (i == 0)
data[i][j] += data[i][j - 1];
else if (j == 0)
data[i][j] += data[i - 1][j];
else
{
int m = min(data[i - 1][j], data[i][j - 1]);
data[i][j] += m;
}
}
cout <<"最小路径: "<< data[2][4] << endl;
system("pause");
return 0;
}