數據結構與算法題目集(中文)7-6 列出連通集 (25分)題解


源代碼:https://github.com/yunwei37/myClassNotes
還有不少數據結構和算法相關的筆記以及pta題解哦x


給定一個有N個頂點和E條邊的無向圖,請用DFS和BFS分別列出其所有的連通集。假設頂點從0到N−1編號。進行搜索時,假設我們總是從編號最小的頂點出發,按編號遞增的順序訪問鄰接點。

輸入格式:

輸入第1行給出2個整數N(0<N≤10)和E,分別是圖的頂點數和邊數。隨後E行,每行給出一條邊的兩個端點。每行中的數字之間用1空格分隔。

輸出格式:

按照"{ v​1​​ v​2​​ … v​k​​ }"的格式,每行輸出一個連通集。先輸出DFS的結果,再輸出BFS的結果。

輸入樣例:

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 }


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

int edge[10][10]={0};
int v[10];
int visit[10]={0};
//dfs
int dfs(int v1,int n){
	int count=1,i;
	cout<<v1<<" ";
	v[v1]=0;
	for(i=0;i<n;++i){
		if(edge[v1][i]&&v[i])
				count+=dfs(i,n);
	}
	return count;
}
//bfs
int bfs(int v1,int n){
	list<int> a;
	int count=1,i,x;
	cout<<v1<<" ";
	v[v1]=0;
	visit[v1]=0;
	for(i=0;i<n;++i)
		if(edge[v1][i])
				a.push_back(i),visit[i]=0;
	while(!a.empty()){
		x=*a.begin();
		a.pop_front();
		cout<<x<<" ";
		v[x]=0;
		++count;
		for(i=0;i<n;++i){
			if(edge[x][i]&&v[i]&&visit[i])
				a.push_back(i),visit[i]=0;
	}
	}
	return count;
}

int main(){
	
	int n,e,n1;
	int i,e1,e2;
	cin>>n>>e;
	for(i=0;i<e;++i){
		cin>>e1>>e2;
		edge[e1][e2]=1;
		edge[e2][e1]=1;
	}
	//dfs 
	for(i=0;i<n;i++)
		v[i]=1;
	n1=n;
	cout<<"{ ";
	n1=n1-dfs(0,n);
	cout<<"}"<<endl;
	while(n1>0){
		i=0;
		while(!v[i])
			++i;
		cout<<"{ ";
		n1-=dfs(i,n);
		cout<<"}"<<endl;
	}
	//bfs
	for(i=0;i<n;++i)
		visit[i]=1;
	for(i=0;i<n;i++)
		v[i]=1;
	n1=n;
	cout<<"{ ";
	n1=n1-bfs(0,n);
	cout<<"}"<<endl;
	while(n1>0){
		i=0;
		while(!v[i])
			++i;
		cout<<"{ ";
		n1-=bfs(i,n);
		cout<<"}"<<endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章