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

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 
#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< q;
	q.push(a);
	vis[a]=1;
	while(!q.empty())
	{
		int x=q.front();
		cout<>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<<"}"<

你可能感兴趣的:(7-79 List Components (25分) 图的dfs bfs)