06-图1. List Components (25)

06-图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 }


图的深度优先搜索和广度优先搜索,用邻接矩阵存储图的关系结构,DFS用递归,BFS用队列。

#include<iostream>
#include<queue>
using namespace std;

#define MaxSize 11
queue<int> q;
struct Graph{
	int data[MaxSize];
	bool Mat[MaxSize][MaxSize];
	int num;
};

bool visited[MaxSize];
void DFS(Graph G,int a)
{
	int i;
	cout<<a<<" ";
	visited[a]=1;
	for(i=0;i<G.num;i++){
		if(G.Mat[a][i]==1 && visited[i]==0){
			DFS(G,i);
		}
	}
}

void DFS_Search(Graph G)
{
	int m;
	for(m=0;m<G.num;m++){
		if(visited[m]==0){
			cout<<"{ ";
			DFS(G,m);
			cout<<"}"<<endl;
		}
	}
}

void BFS(Graph G,int a)
{
	int i;
	cout<<a<<" ";
	visited[a]=1;
	q.push(a);
	while(!q.empty()){
		a=q.front();
		q.pop();
		for(i=0;i<G.num;i++){
			if(visited[i]==0 && G.Mat[a][i]){
				cout<<i<<" ";
				visited[i]=1;
				q.push(i);
			}
		}
	}	
}

void BFS_Search(Graph G)
{
	int m;
	for(m=0;m<G.num;m++){
		if(visited[m]==0){
			cout<<"{ ";
			BFS(G,m);
			cout<<"}"<<endl;
		}
	}
}

int main()
{
	int i,j,N,E,a,b;
	Graph G;
	cin>>N>>E;
	G.num=N;
	for(i=0;i<N;i++){
		for(j=0;j<N;j++)
		G.Mat[i][j]=0;
	}
	for(i=0;i<E;i++){
		cin>>a>>b;
		G.Mat[a][b]=1;
		G.Mat[b][a]=1;
	}
	DFS_Search(G);
	for(i=0;i<N;i++){
		visited[i]=0;
	}
	BFS_Search(G);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值