thought: Figure G is a non-weighted undirected connectivity graph. The length of an edge is counted as 1, so the shortest path to the vertex u and Vertex v is the vertex sequence with the least number of sides of vertex u and Vertex v. Using the breadth-first traversal algorithm, the breadth traversal from U is similar to a layer-by-layer outward expansion from the vertex u, and when the vertex v is first found, the queue includes the recent path from vertex u to vertex v, and then uses the queue output 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++; //Put the non-visited adjacency points of W into the team
qu[rear].data=p->adjvex;
Qu[rear].parent=front;
}
p=p->nextarc;
}
}
}
As you can see, the results of finding the shortest inverse path for vertices 0 to 3 are 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
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 is stored with adjacency table)