#include<stdio.h>
#include<vector>
using namespace std;
void dfs(vector<int> ar[],int visited[],int i,int n){
int j;
visited[i]=1;
printf("%d\n",i);
for(j=0;j<ar[i].size();j++){
if(visited[ar[i][j]]==0){
dfs(ar,visited,ar[i][j],n);
}
}
}
int main(){
int a,b,i,j,n,m;
printf("no of nodes\n");
scanf("%d",&n);
vector<int> ar[n+9];
int visited[n+9];
for(i=0;i<n+9;i++){
visited[i]=0;
}
printf("no of edges\n");
scanf("%d",&m);
for(j=0;j<m;j++){
scanf("%d %d",&a,&b);
ar[a].push_back(b);
ar[b].push_back(a);
}
for(i=1;i<=n;i++){
if(visited[i]==0){
dfs(ar,visited,i,n);
}
}
return 0;
}
#include<vector>
using namespace std;
void dfs(vector<int> ar[],int visited[],int i,int n){
int j;
visited[i]=1;
printf("%d\n",i);
for(j=0;j<ar[i].size();j++){
if(visited[ar[i][j]]==0){
dfs(ar,visited,ar[i][j],n);
}
}
}
int main(){
int a,b,i,j,n,m;
printf("no of nodes\n");
scanf("%d",&n);
vector<int> ar[n+9];
int visited[n+9];
for(i=0;i<n+9;i++){
visited[i]=0;
}
printf("no of edges\n");
scanf("%d",&m);
for(j=0;j<m;j++){
scanf("%d %d",&a,&b);
ar[a].push_back(b);
ar[b].push_back(a);
}
for(i=1;i<=n;i++){
if(visited[i]==0){
dfs(ar,visited,i,n);
}
}
return 0;
}
No comments:
Post a Comment