7-79 List Components (25分) 图的dfs bfs

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 { v
​1
​​ v
​2
​​ … v
​k
​​ }. 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 }

点数较少,可用矩阵存,这样也能保证顺序为从小到大

参考文章
https://www.cnblogs.com/clevercong/p/4198448.html

#include <bits/stdc++.h>
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
const int N=12;
int data[N][N]={0},vis[N]={0};
int n,e;
void dfs(int a)
{
	if(vis[a]) return ;
	cout<<a<<" ";
	vis[a]=1;
	rep(i,0,N-1)
	{
		if(data[a][i]==1 && !vis[i]) dfs(i);
	}
	return ;
}
void bfs(int a)
{
	if(vis[a]) return ;
	queue<int> q;
	q.push(a);
	vis[a]=1;
	while(!q.empty())
	{
		int x=q.front();
		cout<<x<<" ";
		q.pop();
		rep(i,0,N-1)
		{
			if(data[x][i]==1 && !vis[i])
			{
				vis[i]=1;
				q.push(i);
			}
		}
	}
}
int main()
{
	//freopen("D:\\LYJ.txt","r",stdin);
	cin>>n>>e;
	rep(i,0,e-1)
	{
		int a,b;
		cin>>a>>b;
		data[a][b]=1;
		data[b][a]=1;
	}
	rep(i,0,n-1)
	{
		if(!vis[i])
		{
			cout<<"{ ";
			dfs(i);
			cout<<"}"<<endl;
		}
	}
	mem(vis,0);
	rep(i,0,n-1)
	{
		if(!vis[i])
		{
			cout<<"{ ";
			bfs(i);
			cout<<"}"<<endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值