码迷,mamicode.com
首页 > 其他好文 > 详细

05-图1. List Components (25)

时间:2015-07-25 18:33:06      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:浙大pat   mooc   c语言实现   图的遍历   

05-图1. List Components (25)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS and BFS. Assume that all the vertices are numbered from 0 to N-1. While searching, assume that we always start from the vertex with the smallest index, and visit its adjacent vertices in ascending order of their indices.

Input Specification:

Each input file contains one test case. For each case, the first line gives two integers N (0<N<=10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in each line a connected component in the format "{ v1 v2 ... vk }". First print the result obtained by DFS, then by BFS.

Sample Input:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
Sample Output:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

#include <stdio.h>
void DFS(int graph[][10], int *visited, int v, int n, int *ret) {
	visited[v] = 1;
	ret[++ret[0]] = v;
	for (int i = 0; i < n; ++i) {
		if (v != i && graph[v][i] && !visited[i]) {
			DFS(graph, visited, i, n, ret);
		}
	}
}
void BFS(int graph[][10], int *visited, int v, int n) {
	int queque[20] = {};
	int head = 0, rear = 0;
	queque[rear++] = v;							//入队
	visited[v] = 1;
	printf("{ ");
	while (rear > head) {
		int curr = queque[head++];				//出队
		printf("%d ", curr);
		for (int i = 0; i < n; ++i)				//将每个每访问过的邻接节点入队
			if (graph[curr][i] && !visited[i]) {
				visited[i] = 1;
				queque[rear++] = i;
			}
	}
	printf("}\n");
}
int main() {
//	freopen("test.txt", "r", stdin);
	int n, edge;
	scanf("%d%d", &n, &edge);
	int graph[10][10] = {};
	for (int i = 0; i < edge; ++i) {			//邻接矩阵方式构造图
		int v1, v2;
		scanf("%d%d", &v1, &v2);
		graph[v1][v2] = 1;
		graph[v2][v1] = 1;
	}
	int visited[10] = {};
	for (int i = 0; i < n; ++i) {
		int ret[11] = {};						//保存递归遍历到的节点
		if (!visited[i]) {
			DFS(graph, visited, i, n, ret);
			printf("{ ");
			for (int j = 1; j <= ret[0]; ++j) {
				printf("%d ", ret[j]);
			}
			printf("}\n");
		}
	}
	for (int i = 0; i < n; ++i)					//重置已访问标记
		visited[i] = 0;
	for (int i = 0; i < n; ++i) {				//BFS
		if (!visited[i]) {
			BFS(graph, visited, i, n);
		}
	}

	return 0;
}


题目链接:http://www.patest.cn/contests/mooc-ds/05-%E5%9B%BE1

版权声明:本文为博主原创文章,未经博主允许不得转载。

05-图1. List Components (25)

标签:浙大pat   mooc   c语言实现   图的遍历   

原文地址:http://blog.csdn.net/ice_camel/article/details/47058019

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!