Given one has a 1 number. When searching, we assume that we always start from the vertex with the smallest number and access the adjacent points in the order of increasing the number.
Input format:
Input the first line to give two integers n (0 < n ≤ 10) and E, which are vertex number and edge number of graph respectively. Then line e, each line giving two endpoints of an edge. The numbers in each row are separated by 1 space.
Output format:
According to the format of {v1v2.....vk}, each line outputs a connected set. First output DFS results, then output BFS results.
Input example:
8 6 0 7 0 1 2 0 4 1 2 4 3 5
Output example:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 }
#include<bits/stdc++.h> using namespace std; int G[15][15],vis[15]; int n,m; void dfs(int u) { int i; printf(" %d",u); for(i=0;i<n;i++) if(!vis[i]&&G[u][i]) //The point has not been visited and the mark on the map is not 0 { vis[i]=1; //Access complete, marked 1 dfs(i); //Keep searching. } } void bfs(int u) { int i; queue<int> q; q.push(u); //take u Join queue q while(!q.empty()) //If the queue is not empty { u=q.front(); //Team leader element q.pop(); //Team leader out printf(" %d",u); for(i=0;i<n;i++) if(!vis[i]&&G[u][i]) //The point has not been visited and the mark on the map is not 0 { vis[i]=1; //Access complete, marked 1 q.push(i); //take i Join queue q } } } int main() { int i,u,v; scanf("%d%d",&n,&m); //n A vertex. m Strip edge for(i=0;i<m;i++) { scanf("%d%d",&u,&v); //Two vertices per edge u,v G[u][v]=G[v][u]=1; //u-v and v-u Marked 1 } memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) if(!vis[i]) { printf("{"); vis[i]=1; //Access complete, marked 1 dfs(i); //Deep search i printf(" }\n"); } memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) if(!vis[i]) { printf("{"); vis[i]=1; //Access complete, marked 1 bfs(i); //Guang Shu i printf(" }\n"); } return 0; }