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

  测试输入《17. 图的广度优先遍历》 期待的输出《17. 图的广度优先遍历》 时间限制《17. 图的广度优先遍历》 内存限制《17. 图的广度优先遍历》 额外进程《17. 图的广度优先遍历》
测试用例 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;
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/liuyi005/article/details/41855765
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞