邻接表存储 - 无权图的单源最短路算法
关于邻接表的初始化以及插入边的函数,参考之前的博客,点此处跳转,图的邻接表表示法!
此算法包含最短路算法以及路径存储、最短长度、最短路径打印。
参考代码:
#include <cstdio>
#include <string>
#include <stack>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 1010
using namespace std;
int dist[MAX];//记录起点到当前点的最短路径长度
int path[MAX];//记录当前点的路径路线
int S = 1;//起点默认为1
typedef struct ENode
{
int V1, V2;
int Weight;
}*Edge;
struct AdjNode
{
AdjNode *Next;
int Adj;
int Weight;
};
typedef struct ANode
{
AdjNode *Next;
int Data;
}*AdjList[MAX];
typedef struct GNode
{
int Vertex_num;
int EdgeNum;
AdjList G;
}*Graph;
/* 邻接表存储 - 无权图的单源最短路算法 */
void UnWeight(Graph G)
{
//初始化为-1
memset(dist, -1, sizeof(dist));
memset(path, -1, sizeof(path));
dist[S] = 0;//初始化
queue<int> q;
q.push(S);
while(!q.empty())
{
int T = q.front();
q.pop();
//将T的邻接点入队,并记录距离以及路径
for(AdjNode *W = G->G[T]->Next; W; W = W->Next)
{
//若没有访问过
if(dist[W->Adj] == -1)
{
q.push(W->Adj);
//当邻接点的长度等于邻接表头的长度 + 1
dist[W->Adj] = dist[T] + 1;
//当前邻接点指向表头
path[W->Adj] = T;
}
}
}
}
//打印起点S到D的路径,倒序,利用栈
void Print(int D)
{
stack<int> s;
int res;
s.push(D);
while(path[D] != -1)
{
res = path[D];
s.push(res);
D = res;
}
while(!s.empty())
{
cout << s.top() <<" ";
s.pop();
}
}
int main()
{
return 0;
}
本文介绍了一种基于邻接表存储的无权图单源最短路算法,详细展示了算法实现过程,包括最短路径计算、路径存储及打印。通过使用队列进行广度优先搜索,算法能有效地找出从指定起点到图中所有其他顶点的最短路径。
911

被折叠的 条评论
为什么被折叠?



