#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> minPath(vector< vector<int> > graph, int start)
{
//初始化结果数组
vector<int> value;
for (int i = 0; i < graph.size(); i++)
{
value.push_back(9999);
}
value[start] = 0;
//最短路径计算
queue<int> nextPoint;
nextPoint.push(start);
while (!nextPoint.empty())
{
for (int i = 0,next = nextPoint.front(); i < graph[next].size(); i++)
{
if (graph[next][i] !=-1&&value[next] + graph[next][i] < value[i])
{
value[i] = value[next] + graph[next][i];//原来的距离和当前状态的距离
nextPoint.push(i);//存入顶点
}
}
nextPoint.pop();
}
return value;
}
int main()
{
vector< vector<int> > Graph;
//vector<int>value = minPath({
// { 0, 24, 8,15,-1,-1,-1},
// { -1, 0,-1,-1, 6,-1,-1},
// { -1,-1, 0,-1, 7, 3,-1},
// { -1,-1,-1, 0,-1,-1, 4},
// { -1,-1,-1,-1, 0,-1, 9},
// { -1,-1,-1, 5, 2, 0,10},
// { -1, 3,-1,-1,-1,-1, 0}}, 0);
vector<int>value = minPath({
{ 0, 2, 1,-1,-1,-1,-1,-1,-1,-1},
{ 2, 0,-1,10, 7,-1,-1,-1,-1,-1},
{ 1,-1, 0,-1,-1, 1,-1,-1,-1,-1},
{-1,10,-1, 0,-1,-1, 2, 3,-1,-1},
{-1, 7,-1,-1, 0,-1,-1, 1,-1,-1},
{-1,-1, 1,-1,-1, 0,-1,-1, 1,-1},
{-1,-1,-1, 2,-1,-1, 0,-1,-1, 4},
{-1,-1,-1, 3, 1,-1,-1, 0,-1, 1},
{-1,-1,-1,-1,-1, 1,-1,-1, 0, 1},
{-1,-1,-1,-1,-1,-1, 4, 1, 1, 0}}, 1);
for (auto v : value)
{
cout << v << " ";
}
return 0;
}
我也不知道这是啥算法,学完动态规划后就推算出了这么个代码,还算好用,不能有负权值路径,不然算法会失效。