void BFS(AdjGraph* G, int v)
{
int w, i; //w记录出队结点编号
ArcNode* p;
SqQueue* qu; //环形
InitQueue(qu);
int visited[MAXV];
for (int i = 0; i < G->n; i++)
visited[i] = 0;
cout << v;
visited[v] = 1;
enQueue(qu, v);
while (!QueueEmpty(qu))
{
deQueue(qu, w);
p = G->adjlist[w].firstarc; //第w头结点的第一个边结点
while (p != NULL)
{
if (visited[p->adjvex] == 0) //未被访问过
{
cout << p->adjvex; //三步: 输出,做标记,进队
visited[p->adjvex] = 1;
enQueue(qu, p->adjvex);
}
p = p->nextarc;
}
}
cout << endl;
}
非连通图的遍历
void DFS1(AdjGraph* G)
{
int i;
for (int i = 0; i < G->n; i++)
if (visited[i] == 0)
DFS(G, i);
}
void BFS1(AdjGraph* G)
{
int i;
for (int i = 0; i < G->n; i++)
if (visited[i] == 0)
BFS(G, i);
}