日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
有朋友反映让我多加备注,我觉得除非特别惊艳的方法需要说明外,这些基本的方法是容易明白的,当然前提是先搞懂算法的基本思想,希望对你们有用。
运行结果:
Mulgraph.h
#pragma once
#define Max 100
#include <iostream>
using namespace std;
class ArcNode
{
public:
int Vnum;
int weight;
ArcNode *arc_next;
ArcNode()
{
this->arc_next = NULL;
}
ArcNode(int Vnum, ArcNode*arc_next = NULL)
{
this->arc_next = arc_next;
this->Vnum = Vnum;
this->weight = weight;
}
};
typedef struct VNode
{
int data;
ArcNode *firstedge;
}VNode, AdjList[Max];
class ALGraph
{
public:
ALGraph();
void mulgraph(ALGraph&);
int edge_num;
int vexs_num;
AdjList AdjList[Max];
};
Mulgraph.cpp
#include"MulGraph.h"
ALGraph::ALGraph()
{
this->vexs_num = 0;
this->edge_num = 0;
cout << "请输入顶点数和边数:";
cin >> this->vexs_num >> this->edge_num;
ArcNode *p, *q;
cout << endl;
cout << "请输入各顶点:";
for (int i = 0; i < this->vexs_num; i++)
{
cin >> this->AdjList[i]->data;
this->AdjList[i]->firstedge = NULL;
}
cout << endl;
cout << "请输入顶点以及相应的权值:" << endl;
for (int i = 0; i < this->edge_num; i++)
{
int j, k, w;
p = (ArcNode*)malloc(sizeof(ArcNode));
cin >> j >> k >> w;
p->Vnum = k;
p->weight = w;
p->arc_next = this->AdjList[j-1]->firstedge;
this->AdjList[j-1]->firstedge = p;
}
cout << endl;
}
void ALGraph::mulgraph(ALGraph&graph)
{
int *cost = new int[graph.vexs_num];
int *path = new int[graph.vexs_num];
for (int i = 0; i < graph.vexs_num; i++)
{
cost[i] = Max;
path[i] = 0;
}
cost[graph.vexs_num - 1] = 0;
ArcNode *head;
for (int i = graph.vexs_num-1; i >=0; i--)
{
head = graph.AdjList[i]->firstedge;
while (head!=NULL)
{
if (cost[head->Vnum-1]+head->weight < cost[i])
{
cost[i] = cost[head->Vnum-1] + head->weight;
path[i+1] = head->Vnum;
}
head = head->arc_next;
}
}
int mincost;
mincost = cost[0];
int j=1;
while (path[j]!=NULL&&j<graph.vexs_num)
{
cout << path[j]<<" ";
j = path[j];
}
cout << endl;
free(path);
free(cost);
cout << endl;
cout << "最短路径的总代价为:"<<mincost;
cout << endl;
}
int main()
{
ALGraph graph;
cout << "最短路径为:"<<graph.AdjList[0]->data<<" ";
graph.mulgraph(graph);
return 0;
}