17. 图的广度优先遍历

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个顶点开始进行遍历,输出为图的邻接表和广度优先遍历序列。例如:

程序输入为:






*
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

  测试输入关于“测试输入”的帮助 期待的输出关于“期待的输出”的帮助 时间限制关于“时间限制”的帮助 内存限制关于“内存限制”的帮助 额外进程关于“{$a} 个额外进程”的帮助
测试用例 1 以文本方式显示
  1. a↵
  2. b↵
  3. c↵
  4. d↵
  5. e↵
  6. f↵
  7. *↵
  8. 0,1↵
  9. 0,4↵
  10. 1,4↵
  11. 1,5↵
  12. 2,3↵
  13. 2,5↵
  14. 3,5↵
  15. -1,-1↵
以文本方式显示
  1. the ALGraph is↵
  2. a 4 1↵
  3. b 5 4 0↵
  4. c 5 3↵
  5. d 5 2↵
  6. e 1 0↵
  7. f 3 2 1↵
  8. the Breadth-First-Seacrh list:aebfdc↵
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;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值