加载中...

C++实现矩阵求最短路径

点击查看代码
#include "iostream"
#include "math.h"
#include "stdio.h"
#include "limits.h"
using namespace std;


#define yLength 10
#define xLength 1000
int calculateShortestPath( int matrix[xLength][yLength])
{
        int temp[xLength][yLength];
        temp[0][0] = 0;
        for(int i=1; i<xLength; i++)
        {
                temp[i][0] = temp[i-1][0] + matrix[i][0];
        }

          for(int i=1; i<yLength; i++)
        {
                temp[0][i] = temp[0][i-1] + matrix[0][i];
        }

        for(int i=1; i<xLength; i++)
        {
              for(int j=1;  j<yLength;  j++)
                {
                    if(temp[i][j-1]<temp[i-1][j])
                    {
                        temp[i][j] = temp[i][j-1] + matrix[i][j];
                    }
                    else
                    {
                         temp[i][j] = temp[i-1][j] + matrix[i][j];
                    }
                }
        }
        return temp[xLength-1][yLength-1];
}


int main()
{
    int matrix[xLength][yLength];

    for(int i=0; i<xLength; i++)
    {
        for(int j=0; j<yLength; j++)
        {
            matrix[i][j] = rand()%10;
        }
    }
    cout<<calculateShortestPath(matrix) << endl;
    return 0;
}
posted @ 2022-07-06 22:09  微微微  阅读(132)  评论(0编辑  收藏  举报