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,分别使用stack和queue作辅助。
/*2015.7.15cyq*/ #include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; //深度搜索DFS,使用一个stack作辅助 vector<vector<int> > DFS(const vector<vector<bool> > &edges,const int &N){ vector<vector<int> > result; vector<int> path;//单个子图DFS序列 stack<int> stk; vector<bool> visited(N,false); for(int i=0;i<N;i++){ if(!visited[i]){ stk.push(i); while(!stk.empty()){ int root=stk.top(); stk.pop(); if(!visited[root]){//有可能该结点很早就被压入,因值较大本来要放在最后处理 visited[root]=true; //但深搜时回环被其他结点再次压入,反而较早被访问过 path.push_back(root); for(int j=N-1;j>=0;j--){//大的先压入stck,保证小的先弹出处理 if(edges[root][j]&&!visited[j]){ stk.push(j); } } } } result.push_back(path); path.clear(); } } return result; } //广度搜索BFS,使用两个queue作辅助,表示当前层和下一层 vector<vector<int> > BFS(const vector<vector<bool> > &edges,const int &N){ vector<vector<int> > result; vector<int> path;//单个子图BFS序列 queue<int> cur,next;//当前层和下一层 vector<bool> visited(N,false); for(int i=0;i<N;i++){ if(!visited[i]){ cur.push(i); visited[i]=true;//与DFS不同,一层一层往外,不存在回环,只要入队就可标记为使用过 while(!cur.empty()){ while(!cur.empty()){ int root=cur.front(); cur.pop(); path.push_back(root); for(int j=0;j<N;j++){//从小到大入队 if(edges[root][j]&&!visited[j]){ next.push(j); visited[j]=true; } } } swap(cur,next); } result.push_back(path); path.clear(); } } return result; } int main(){ int N,E; cin>>N>>E; vector<int> vexs(N); for(int i=0;i<N;i++) vexs[i]=i; vector<vector<bool> > edges(N,vector<bool>(N,false)); int a,b; for(int i=0;i<E;i++){ cin>>a>>b; edges[a][b]=true; edges[b][a]=true; } vector<vector<int> > result=DFS(edges,N); for(auto it=result.begin();it!=result.end();it++){ int k=(*it).size(); cout<<"{"; for(auto itt=(*it).begin();itt!=(*it).end();itt++) cout<<" "<<*itt; cout<<" }"<<endl; } vector<vector<int> > result1=BFS(edges,N); for(auto it=result1.begin();it!=result1.end();it++){ int k=(*it).size(); cout<<"{"; for(auto itt=(*it).begin();itt!=(*it).end();itt++) cout<<" "<<*itt; cout<<" }"<<endl; } return 0; }