17. 图的广度优先遍历
成绩 | 10 | 开启时间 | 2014年11月26日 Wednesday 14:00 |
折扣 | 0.8 | 折扣时间 | 2014年12月7日 Sunday 23:55 |
允许迟交 | 否 | 关闭时间 | 2014年12月14日 Sunday 23:55 |
本实验实现邻接表表示下无向图的广度优先遍历。
程序的输入是图的顶点序列和边序列(顶点为单个字符,顶点序列以*为结束标志;边序列以-1,-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 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct Node{
char data;
int flag;
int Near[500];
int num;
}List[500];
int main()
{
int i = 0;
int j;
int count_point;
int lpoint, rpoint;
char temp[5];
queue <Node> T;
while (1){
scanf("%s", temp);
if (temp[0] == '*')
break;
List[i].data = temp[0];
List[i].flag = 0;
List[i].num = 0;
i++;
}
count_point = i;
while (1){
scanf("%d,%d", &lpoint, &rpoint);
if (lpoint == -1 && rpoint == -1)
break;
List[lpoint].Near[List[lpoint].num] = rpoint;
List[lpoint].num++;
List[rpoint].Near[List[rpoint].num] = lpoint;
List[rpoint].num++;
}
printf("the ALGraph is\n");
for (i = 0; i < count_point; i++){
printf("%c", List[i].data);
for (j = List[i].num - 1; j >= 0; j--)
printf(" %d", List[i].Near[j]);
printf("\n");
}
printf("the Breadth-First-Seacrh list:");
for (i = 0; i < count_point; i++){
if (List[i].flag == 0){
T.push(List[i]);
List[i].flag = 1;
struct Node now;
while (!T.empty()){
now = T.front();
printf("%c", now.data);
for (j = now.num - 1; j >= 0; j--){
if (List[now.Near[j]].flag == 0){
List[now.Near[j]].flag = 1;
T.push(List[now.Near[j]]);
}
}
T.pop();
}
}
}
printf("\n");
return 0;
}