sicily 4378 connected components in undirected graph

题意:求图中的连通块数,注意孤立的算自连通!

         例如:6个顶点3条路径,其中路径为:1->2    4->5  1->3

                  那么有(1-2&&1->3) + (4->5) + (6) 共3个连通块!

解法:对每个节点宽搜!

 

 1 #include<iostream>

 2 #include<memory.h>

 3 #include<queue>

 4 

 5 using namespace std;

 6 

 7 bool roads[1001][1001];

 8 bool visited[1001];

 9 int N,M;

10 

11 int main(){

12 

13     cin >>N >>M;

14     memset(roads,0,sizeof(roads));

15     memset(visited,false,sizeof(visited));

16     int from,dest;    

17     for(int i=1; i<=M; i++){

18         cin >> from >> dest;

19         roads[from][dest] = true;

20         roads[dest][from] = true;

21     }

22 

23     queue<int> check;

24     int num = 0;

25     int cnt = 0;

26     int i;

27     //breadth-frist search

28     while(num != N){

29         for( i=1; i<=N;i++){

30             if(visited[i]== false){

31                 check.push(i);

32                 visited[i]= true;

33                 num++;

34                 cnt++;

35                 break;

36             }

37         }

38         while(!check.empty()){

39             i = check.front();

40             for(int j = 1; j<=N;j++){

41                 if(roads[i][j] == true && visited[j] == false){            

42                     check.push(j);

43                     visited[j] = true;

44                     num++;

45                 }

46             }

47             // erase the front node

48             check.pop();

49         }

50     }

51     cout << cnt <<endl;

52     return 0;

53 }

 

 

你可能感兴趣的:(component)