(数据结构)图的广度优先遍历
本实验实现邻接表表示下无向图的广度优先遍历。
程序的输入是图的顶点序列和边序列(顶点序列以*为结束标志,边序列以-1,-1为结束标志)。程序的输出为图的邻接表和广度优先遍历序列。例如:
程序输入为:
a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1
程序的输出为:
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc
测试用例1:
测试输入:
a↵
b↵
c↵
d↵
e↵
f↵
*↵
0,1↵
0,4↵
1,4↵
1,5↵
2,3↵
2,5↵
3,5↵
-1,-1↵
期待的输出:
the ALGraph is↵
a 4 1↵
b 5 4 0↵
c 5 3↵
d 5 2↵
e 1 0↵
f 3 2 1↵
the Breadth-First-Seacrh list:aebfdc↵
代码如下:
#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct
{
string name;
int sonList[100];
int sonNum = 0;
int vir = 0;
}Node[100];
int num = 0, nx, ny;
void BFS(int x)
{
queue<int>q;
int k0 = x, k1;
Node[k0].vir = 1;
q.push(k0);
while (!q.empty())
{
k0 = q.front();
q.pop();
cout << Node[k0].name;
if (Node[k0].sonNum == 0)
continue;
for (int i = Node[k0].sonNum - 1; i >= 0; i--)
{
k1 = Node[k0].sonList[i];
if (Node[k1].vir == 1)
continue;
q.push(k1);
Node[k1].vir = 1;
}
}
}
int main()
{
while (1)
{
cin >> Node[num].name;
if (Node[num].name == "*")
break;
num++;
}
while (1)
{
scanf("%d,%d", &nx, &ny);
if (nx == -1)
break;
Node[nx].sonList[Node[nx].sonNum] = ny;
Node[nx].sonNum++;
Node[ny].sonList[Node[ny].sonNum] = nx;
Node[ny].sonNum++;
}
cout << "the ALGraph is" << endl;
for (int i = 0; i < num; i++)
{
cout << Node[i].name;
for (int j = Node[i].sonNum - 1; j >= 0; j--)
cout << " " << Node[i].sonList[j];
cout << endl;
}
cout << "the Breadth-First-Seacrh list:";
for (int i = 0; i < num; i++)
{
if (Node[i].vir == 0)
BFS(i);
}
cout << endl;
return 0;
}