列出连通集

列出连通集_第1张图片

输入样例:

8 6
0 7
0 1
2 0
4 1
2 4
3 5

输出样例:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

solution

#include 
#include 
int arcs[10][10];
int visited[10] = {0};
void DFS(int n, int v);
void BFS(int n , int i);
int main(){
	int n, e, v1, v2;
	memset(arcs, 0, sizeof(arcs));
	scanf("%d%d", &n, &e);
	for(int i = 0; i < e; i++){
		scanf("%d%d", &v1, &v2);
		arcs[v1][v2] = arcs[v2][v1] = 1;
	}
	for(int i = 0; i < n; i++){
		if(!visited[i]){
			printf("{");
			DFS(n, i);
			printf(" }\n");
		}
	}
	memset(visited, 0, sizeof(visited));
	for(int i = 0; i < n; i++){
		if(!visited[i]){
			printf("{");
			BFS(n, i);
			printf(" }\n");
		}
	}
	return 0;
}

void DFS(int n, int v){
	printf(" %d", v);
	visited[v] = 1;
	for(int i = 0; i < n; i++){
		if(arcs[v][i] && !visited[i] )
			DFS(n, i);
	}
}

void BFS(int n , int i){
	int q[n], rear = 0, front = 0; 
	printf(" %d", i);
	visited[i] = 1;
	q[rear++] = i;
	while(rear != front){
		int t = q[front++];
		for(int j = 0; j < n; j++){
			if(!visited[j] && arcs[t][j]){
				printf(" %d", j);
				visited[j] = 1;
				q[rear++] = j;
			}
		}
	}
}

你可能感兴趣的:(pat,深度优先,算法,图论)