码迷,mamicode.com
首页 > 其他好文 > 详细

PAT List Components

时间:2015-05-27 09:44:09      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

List Components

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.

 

给定 顶点数N 边数E 以及 顶点的连通关系

分别求DFS和BFS 的遍历

 1 #include "stdio.h"
 2 
 3 int flag[10];
 4 int graph[10][10];
 5 int v,e;
 6 void DFS(int i)
 7 {
 8     int j;
 9     printf("%d ",i);
10     flag[i]=1;
11     for(j=0;j<v;j++)
12     {
13         if(graph[i][j]==1 && flag[j]!=1)
14             DFS(j);
15     }
16 }
17 void BFS(int i)
18 {
19     int start,end,q[10],temp,j;
20     start=end=0;
21     q[end++]=i;
22     flag[i]=1;
23     while(start<end)
24     {
25         temp=q[start];
26         start++;
27         printf("%d ",temp);
28         for(j=0;j<v;j++)
29         {
30             if(graph[temp][j]==1 && flag[j]!=1)
31             {
32                 q[end++]=j;
33                 flag[j]=1;
34             }
35         }
36     }
37     
38 }
39 main()
40 {
41     int i,m,n;
42     scanf("%d%d",&v,&e);
43     for(i=0;i<e;i++)
44     {
45         scanf("%d%d",&m,&n);
46         graph[m][n]=graph[n][m]=1;
47     }
48     for(i=0;i<v;i++)
49     {
50         if(flag[i]==1)
51             continue;
52         else
53         {    
54             printf("{ ");
55             DFS(i);    
56             printf("}\n");    
57         }
58     }
59     for(i=0;i<v;i++)
60         flag[i]=0;
61     for(i=0;i<v;i++)
62     {
63         if(flag[i]==1)
64             continue;
65         else
66         {    
67             printf("{ ");
68             BFS(i);    
69             printf("}\n");    
70         }
71     }
72 }

 

PAT List Components

标签:

原文地址:http://www.cnblogs.com/threezj/p/4532546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!