時間限制
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 5Sample Output:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 } { 6 }
#include <iostream>
#include <string.h>
#include <queue>
#define MAX 100
#define N 11
using namespace std;
typedef struct
{
int vertexnum,edgenum;
int arcs[MAX][MAX];
}MGraph;
bool visit[N];
queue<int> que;
void BFS(MGraph graph, int v)
{
visit[v]=true;
que.push(v);
cout<<"{ "<<v;
while(!que.empty())
{
v=que.front();
//cout<<" "<<v;
que.pop();
for(int i=0;i<graph.vertexnum;i++)
{
if(graph.arcs[v][i]==1&&!visit[i])
{
visit[i]=true;
cout<<" "<<i;
que.push(i);
}
}
}
cout<<" }\n";
}
void allBFS(MGraph graph)
{
for(int v=0;v<graph.vertexnum;v++)
{
if(!visit[v])
{
BFS(graph,v);
//cout<<endl;
}
}
}
void DFS(MGraph graph, int v)
{
visit[v]=true;
for(int i=0;i<graph.vertexnum;i++)
{
if(graph.arcs[v][i]==1&&!visit[i])
{
cout<<i<<" ";
visit[i]=true;
DFS(graph,i);
}
}
}
void allDFS(MGraph graph)
{
for(int v=0;v<graph.vertexnum;v++)
{
if(!visit[v])
{
cout<<"{ "<<v<<" ";
DFS(graph,v);
cout<<"}\n";
}
}
}
int main()
{
int i,j,edge;
MGraph graph;
cin>>graph.vertexnum>>graph.edgenum;
memset(graph.arcs,0,graph.vertexnum*graph.vertexnum);
memset(visit,false,graph.vertexnum);
edge = graph.edgenum;
while(edge--)
{
cin>>i>>j;
visit[i]=true;
visit[j]=true;
graph.arcs[i][j]=1;
graph.arcs[j][i]=1;
}
for(i=0;i<graph.vertexnum;i++)
if(!visit[i])
graph.arcs[i][i]=1;
memset(visit,false,graph.vertexnum);
allDFS(graph);
memset(visit,false,graph.vertexnum);
allBFS(graph);
return 0;
}