Connect

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
int G[40][40], mark[40], n;
void dfs(int u, int c) {
mark[u]=c;
for(int v=1; v<=n; v++) {
if((G[u][v]==1) && mark[v]!=c) {
dfs(v,c);
}
}
}
int main() {
freopen("connect.in", "r", stdin);
freopen("connect.out", "w", stdout);
int m;
scanf("%d %d\n", &n, &m);
int b,e;
for(int i=0; i<20; i++) mark[i]=0;
for(int i=0; i<m; i++) {
scanf("%d %d\n", &b, &e);
G[b][e]=1;
G[e][b]=1;
}
int count=0, col=1;
for(int i=1; i<=n; i++) if(mark[i]==0) {
dfs(i, col++); count++;
}
printf("%d", count);
return 0;
}