06-图1. List Components (25)
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 }
图的深度优先搜索和广度优先搜索,用邻接矩阵存储图的关系结构,DFS用递归,BFS用队列。
#include<iostream>
#include<queue>
using namespace std;
#define MaxSize 11
queue<int> q;
struct Graph{
int data[MaxSize];
bool Mat[MaxSize][MaxSize];
int num;
};
bool visited[MaxSize];
void DFS(Graph G,int a)
{
int i;
cout<<a<<" ";
visited[a]=1;
for(i=0;i<G.num;i++){
if(G.Mat[a][i]==1 && visited[i]==0){
DFS(G,i);
}
}
}
void DFS_Search(Graph G)
{
int m;
for(m=0;m<G.num;m++){
if(visited[m]==0){
cout<<"{ ";
DFS(G,m);
cout<<"}"<<endl;
}
}
}
void BFS(Graph G,int a)
{
int i;
cout<<a<<" ";
visited[a]=1;
q.push(a);
while(!q.empty()){
a=q.front();
q.pop();
for(i=0;i<G.num;i++){
if(visited[i]==0 && G.Mat[a][i]){
cout<<i<<" ";
visited[i]=1;
q.push(i);
}
}
}
}
void BFS_Search(Graph G)
{
int m;
for(m=0;m<G.num;m++){
if(visited[m]==0){
cout<<"{ ";
BFS(G,m);
cout<<"}"<<endl;
}
}
}
int main()
{
int i,j,N,E,a,b;
Graph G;
cin>>N>>E;
G.num=N;
for(i=0;i<N;i++){
for(j=0;j<N;j++)
G.Mat[i][j]=0;
}
for(i=0;i<E;i++){
cin>>a>>b;
G.Mat[a][b]=1;
G.Mat[b][a]=1;
}
DFS_Search(G);
for(i=0;i<N;i++){
visited[i]=0;
}
BFS_Search(G);
return 0;
}