thought: Figure G is a non-weighted undirected graph with a length of 1, so the shortest path to the vertex u and Vertex v is the vertex sequence with the least number of vertices in the vertex u and Vertex v. Using the breadth-first traversal algorithm, the breadth traversal from u, similar to the one-layer outward expansion from vertex u, when the vertex v is first found, contains the closest path from vertex u to vertex v, and then uses the queue to output the most path (inverse path), so it is designed as a non-cyclic queue.
The corresponding algorithm is as follows:
typedef struct
{
int data; //Vertex number
int parent; //position of the previous vertex
} QUEUE; //non-circular queue type
void ShortPath (Agraph *g,int u, int v)
{
The shortest inverse path of the output from vertex u to vertex v
Arcnode *p;
int w,i;
QUEUE QU[MAXV]; //non-circular queue
int front=-1,rear=-1; //queue tail pointer
int VISITED[MAXV];
for (i=0;i<g->n;i++)//Access flag set initial value 0
visited[i]=0;
rear++;
Qu[rear].data=u; //vertex u into Team
Qu[rear].parent=-1;
Visited[u]=1;
while (front<=rear)//queue is not empty when looping
{
front++;
W=qu[front].data; //out of the team vertex W
if (w==v)//The inverse of the output path when V is found and exits
{
I=front; //Output reverse path via queue
while (Qu[i].parent!=-1)
{
printf ("%2d", qu[i].data);
I=qu[i].parent;
}
printf ("%2d\n", qu[i].data);
Break
}
p=g->adjlist[w].firstarc; //Find First adjacency point of W
while (P!=null)
{
if (visited[p->adjvex]==0)
{
visited[p->adjvex]=1;
rear++; //Add the inaccessible adjacency points of W into the team
qu[rear].data=p->adjvex;
Qu[rear].parent=front;
}
p=p->nextarc;
}
}
}
, the result of finding the shortest inverse path from vertex 0 to 3 is as follows:
adjacency table:
"0": 1->4->^
"1": 0->2->3->^
"2": 1->2->^
"3": 1->2->^
"4": 0->2->^
Shortest inverse path of vertex 0 to Vertex 3:3 1 0
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Design an algorithm that uses BFS to output the shortest path from vertex u to V in the graph G (non-weighted undirected connectivity graph G with adjacency table storage)