图的广度优先搜索遍历根树的层次遍历类似
首先访问其实顶点v,然后选取与v邻接的全部顶点w0,w1,w2……进行访问,再依次访问与w0,w1,w2……..邻接的所有顶点,依此类推
也就是说用到一个队列
首先让一个顶点入队
如果队列不空的话:出对,依次检查出对顶点的所有邻接顶点,访问没有被访问过的邻接顶点并将其入队
队列为空:跳出循环
void BFS(AGraph G, int v, int visit[MAX_VERTEX_NUM])
{
ArcNode *p;
int que[MAX_VERTEX_NUM], front = 0, rear = 0;
int j;
cout << v << " ";
visit[v] = 1;
rear = (rear + 1) % MAX_VERTEX_NUM;
que[rear] = v;
while (front != rear)
{
front = (front + 1) % MAX_VERTEX_NUM;
j = que[front];
p = G.adjlist[j].firstarc;
while (p)
{
if (visit[p->adjvex] == 0)
{
cout << p->adjvex;
visit[p->adjvex] = 1;
rear = (rear + 1) % MAX_VERTEX_NUM;
que[rear] = p->adjvex;
}
p = p->nextarc;
}
}
}