本实验实现邻接表表示下无向图的广度优先遍历。程序的输入是图的顶点序列和边序列(顶点序列以*为结束标志,边序列以-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
#include<cstdio>
#include<string>
#include<map>
#include<stack>
#include<math.h>
#include<iostream>
#include<queue>
using namespace std;
map<char, int> points;
map<char, int> Ispass;
map<int, char> getpoints;
map<char, int> Num;
queue<char> Q;
int ALGraph[50][50];
int main()
{
//freopen("1.txt", "r", stdin);
int k = 0; //点的个数
char point;
while (scanf("%c\n", &point))
{
if (point == '*')
break;
points.insert(pair<char, int>(point, k));
getpoints.insert(pair<int, char>(k,point));
Ispass.insert(pair<char, int>(point, 0));
Num.insert(pair<char, int>(point, 0));
k++;
}
int a, b;
while (scanf("%d,%d", &a, &b))
{
if (a == -1 && b == -1)
break;
ALGraph[a][b] = ALGraph[b][a] = 1;
Num[getpoints.find(a)->second]++;
Num[getpoints.find(b)->second]++;
}
printf("the ALGraph is\n");
for (int i = 0; i < k; i++)
{
printf("%c", getpoints.find(i)->second);
//int num_of_1 = Num.find(getpoints.find(i)->second)->second;
for (int j = k - 1; j >= 0; j--)
{
if (ALGraph[i][j]!=0&&i==j)
{
printf(" %d %d", j, j);
continue;
}
if (ALGraph[i][j] != 0)
printf(" %d", j);
}
printf("\n");
}
char tmp;
printf("the Breadth-First-Seacrh list:");
for (int p = 0; p < k; p++)
{
tmp = getpoints[p];
if (!Ispass[tmp])
{
Ispass[tmp] = 1;
printf("%c", tmp);
Q.push(tmp);
while (!Q.empty())
{
int i = points[Q.front()];
Q.pop();
for (int m = k - 1; m >= 0; m--)
{
if (ALGraph[i][m])
{
tmp = getpoints[m];
if (!Ispass[tmp])
{
Q.push(tmp);
Ispass[tmp] = 1;
printf("%c", tmp);
}
}
}
}
}
}
printf("\n");
return 0;
}