本文在图的深度遍历的基础上,添加了dijkstra算法,简单实现了最短路径的选择。理论知识不在论述,以下代码仅供参考(博主刚学了dijkstra算法)。
#include<iostream>
#include<vector>
using namespace std;
#define MAXSIZE 100
typedef struct EdgeNode{
int weight;
int y;
struct EdgeNode *next;
}EdgeNode;
typedef struct VectexNode{
int data;
EdgeNode* firstNode;
}VectexNode,VectexList[MAXSIZE];
typedef struct Graph{
int numEdge;
int numVectex;
VectexList veclist;
}Graph;
void initialGraph(Graph *g)
{
int i,j,k,weight;
EdgeNode* e;
cout<<"请输入顶点数与边数"<<endl;
cin>>g->numVectex>>g->numEdge;
for(i = 0;i<g->numVectex;++i)
{
cout<<"请输入顶点的数据"<<endl;
cin>>g->veclist[i].data;
g->veclist[i].firstNode = nullptr;
}
for(k = 0;k<g->numVectex;++k)
{
cout<<"请输入(Vi,Vj)上的顶点序号及权重"<<endl;
cin>>i>>j>>weight;
e = new EdgeNode;
e->weight = weight;
e->y = j;
e->next = g->veclist[i].firstNode;
g->veclist[i].firstNode = e;
}
}
void DFS(Graph *g,int i,bool visited[MAXSIZE])
{
cout<<"深度优先遍历之-> 图的数据为:"<<g->veclist[i].data<<endl;
visited[i] = true;
EdgeNode *e = g->veclist[i].firstNode;
while(e)
{
if(!visited[e->y])
{
DFS(g,e->y,visited);
}
e = e->next;
}
}
void DFSReverse(Graph *g)
{
bool visited[MAXSIZE];
for(int i = 0;i<g->numVectex;i++)
{
visited[i]= false;
}
for(int i = 0;i<g->numVectex;i++)
{
DFS(g,i,visited);
}
}
void dijkstraAlgo(Graph *g, int start) {
bool visited[MAXSIZE] = {false};
int dist[MAXSIZE];
int parent[MAXSIZE];
for (int i = 0; i < g->numVectex; ++i) {
dist[i] = INT_MAX;
parent[i] = -1;
}
dist[start] = 0;
for (int count = 0; count < g->numVectex - 1; ++count) {
int u, minDist = INT_MAX;
for (int v = 0; v < g->numVectex; ++v) {
if (!visited[v] && dist[v] <= minDist) {
minDist = dist[v];
u = v;
}
}
visited[u] = true;
EdgeNode *e = g->veclist[u].firstNode;
while (e) {
int v = e->y;
if (!visited[v] && dist[u] != INT_MAX && dist[u] + e->weight < dist[v]) {
dist[v] = dist[u] + e->weight;
parent[v] = u;
}
e = e->next;
}
}
for (int i = 0; i < g->numVectex; ++i) {
cout << "从顶点 " << start << " 到顶点 " << i << " 的最短路径距离为: " << dist[i] << endl;
}
}
int main()
{
Graph g;
initialGraph(&g);
dijkstraAlgo(&g,1);
system("pause");
return 0;
}