int temp[MAX] = { -1 };//采用一个数组来存放已经访问过的数据,再利用这个数组往下继续广度遍历
int j = 0, infront = -1;//infront用于控制这个用于广度遍历的数组
int visited[MAX] = {0};
int n = 0;
void ALGraphBFS(ALGraph* G, int v)
{
ArcNode* p;
int w, i;
if (visited[v] != 1)
{
printf("%s", G->vertex[v].data);
visited[v] = 1;
n++;
}
p = G->vertex[v].nextarc;
while (p != NULL)
{
if (visited[p->index] != 1)
{
printf("%s", G->vertex[p->index].data);
visited[p->index] = 1;
if (n < G->vexnum)
{
n++;
}
temp[j] = p->index;//先记录下需要进行下一次广度优先搜索的下标
j++;
}
p = p->next;
}
if (p == NULL)
{
if (n == G->vexnum)
{
return;
}
if (temp[infront + 1] != -1)
{
infront++;
}
ALGraphBFS(G, temp[infront]);
}
}
int main(int argc, char* argv[])
{
ALGraph* G;
CreateALGraph(G);
PrintALGraph(G);
printf("邻接表的广度优先遍历顺序为:");
ALGraphBFS(G, 0);
printf("\n");
DestroyALGraph(G);
return 0;
}
邻接表的广度优先遍历
最新推荐文章于 2024-07-25 21:08:08 发布