单源无权最短路(邻接表)
先构建邻接表
typedef int Vertex; //邻接表, 单链表中的节点 typedef struct ArcNode { int to; struct ArcNode *next; }ArcNode; //顶点, 其中包含顶点编号,和与他相连的第一个顶点作为第一个头节点 typedef struct Node { Vertex id; ArcNode *first; } //图 typedef struct LGraph { Node G[MaxVertexNum]; int v, e; }
单源无权最短路算法
void NoWeightShortestPath(int dist[], Vertex path[], LGraph& g, Vertex id) { //自定义的一个简单的队列 Queue q; q.push(id); dist[id] = 0; while(!q.empyt()) { Vertex p = q.pop(); ArcNode *t = g.G[p].first; while(t->next) { if(dist[t->to] == -1) { dist[t->to] = dist[p] + 1; path[t->to] = p; q.push(t->to); } } } }