List Components

List Components

题目:

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS (Depth First Search) and BFS (Breadth First Search). 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.

输入:

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 }

因为题目中要求能连接的数写在同一个集合里,所以在搜索的过程中需要先遍历每一个遍历完一轮后就换行,以深搜为例:
思路代码:

for(int i=0;i<n;i++)
	{
		if(visited[i]==0)	//只有确保遍历到的数还没搜过才深搜他
		{
			cout<<"{ ";
			dfs(i);
			cout<<'}'<<endl;
		}		
	}

在代码里广搜运用了队列结构来模拟一层一层遍历,当队列中的头队列连接的数都遍历完了之后就可以遍历下一层了
思路代码:

for(int j=0;j<n;j++)
		{
			if(b[q.front()][j]==1&&visited[j]==0)
			{
				q.push(j);
				visited[j]=1;
			}
		}

完整代码过程

#include<bits/stdc++.h>
using namespace std;
//用于初始化 
const int INF=0x3ffffff;
int n,e,sum;
int a[101][101],b[101][101],visited[101];
//深搜 
void dfs(int i)
{
	
	cout<<i<<" "; 
	visited[i]=1;
	int j;
	
	sum++;
	if(sum==n) return;  
	for(j=0;j<n;j++)
	{
		if(visited[j]==0&&a[i][j]==1) 
		{
			visited[j]=1; 
			dfs(j); 
		}
	}	
	return ;
	
}
//广搜 
void bfs(int i)
{
	visited[i]=1;
	queue<int> q;
	q.push(i);
	while(!q.empty())
	{
		for(int j=0;j<n;j++)
		{
			if(b[q.front()][j]==1&&visited[j]==0)
			{
				q.push(j);
				visited[j]=1;
			}
		}
		cout<<q.front()<<" ";
		q.pop();
	}
 } 
int main()
{
	int i,j;
	int v,u;
	memset(visited,0,sizeof(visited));
	cin>>n>>e;
	//初始化深搜用的数组 
	for(i=0;i<n;i++) 
	{
		for(j=0;j<n;j++)
			if(i==j) a[i][j]=1; 
			else a[i][j]=INF;
	}
	//初始化广搜搜用的数组 
	for(i=0;i<n;i++) 
	{
		for(j=0;j<n;j++)
			if(i==j) b[i][j]=1; 
			else b[i][j]=INF;
	}
	
	for(int i=0;i<e;i++)
	{
		cin>>v>>u;
		//深搜数组 
		a[v][u]=1;
		a[u][v]=1;
		//广搜数组 
		b[v][u]=1;
		b[u][v]=1;
	}
	sum=1;
	//深搜 
	for(int i=0;i<n;i++)
	{
		if(visited[i]==0)
		{
			cout<<"{ ";
			dfs(i);
			cout<<'}'<<endl;
		}		
	}

	//广搜
	sum=1;

	memset(visited,0,sizeof(visited));
	for(int i=0;i<n;i++)
	{
		if(visited[i]==0)
		{
			cout<<"{ ";
			bfs(i);
			cout<<'}'<<endl;
		}
	}
			
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值