图的广度优先遍历(《啊哈,算法》模板)
作者:
boxyit
,
2020-08-04 11:51:07
,
所有人可见
,
阅读 673
C语言代码,采用邻接矩阵存储无向图
#include <stdio.h>
int book[110] = {0}, e[110][110];
int n;
int que[10010], head, tail;
int main()
{
scanf("%d", &n);
int i, j;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
if(i == j)
e[i][j] = 0;
else
e[i][j] = 99999999;
}
}
int a, b;
for(i = 1; i <= n; i++)
{
scanf("%d %d", &a, &b);
e[a][b] = 1;
e[b][a] = 1;
}
head = 1;
tail = 1;
que[tail] = 1;
tail++;
book[1] = 1;
int cur;
while(head < tail && tail <= n)
{
cur = que[head];
for(i = 1; i <= n; i++)
{
if(e[cur][i] == 1 && book[i] == 0)
{
book[i] = 1;
que[tail] = i;
tail++;
}
if(tail > n)
break;
}
head++;
}
for(i = 1; i < tail; i++)
printf("%d ", que[i]);
return 0;
}
输入样例:
5
1 2
1 3
1 5
2 4
3 5
输出:
1 2 3 5 4