c编写List Components

本文介绍了一个给定无向图中所有连通分量的求解方法,分别使用深度优先搜索(DFS)和广度优先搜索(BFS)两种经典算法进行实现,并提供了完整的C语言代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 List Components   (10分)

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS (Depth First Search) and BFS (Breadth First Search). 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.

Input Specification:

Each input file contains one test case. For each case, the first line gives two integers N (0<<N\le10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in each line a connected component in the format { v_1v1 v_2v2 ... v_kvk }. First print the result obtained by DFS, then by BFS.

Sample Input:

8 6
0 7
0 1
2 0
4 1
2 4
3 5

Sample Output:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }

{ 6 }

#include<stdio.h> int N,E; int graph[20][20]={-1}; int visited[20]={0}; int queue[20]={-1}; void DFS(int v); void BFS(int v,int front,int rear); int main(void) { int v1,v2; int i=0; scanf("%d%d",&N,&E); for(i=0;i<E;i++){ scanf("%d%d",&v1,&v2); graph[v1][v2]=1; graph[v2][v1]=1; } for(i=0;i<N;i++){ if(visited[i]!=0) continue; else{ printf("{"); DFS(i); printf(" }\n"); } } for(i=0;i<N;i++) visited[i]=0; for(i=0;i<N;i++){ if(visited[i]!=0) continue; else{ visited[i]=1; queue[0]=i; printf("{"); BFS(i,0,1); printf(" }\n"); } } return 0; } void DFS(int v) { int w; visited[v]=1; printf(" %d",v); for(w=0;w<N;w++){ if(graph[v][w]==1){ if(visited[w]==0) DFS(w); } } } void BFS(int v,int front,int rear) {     int w; while(1){ for(w=0;w<N;w++){ if(graph[v][w]==1){ if(visited[w]==0){ queue[rear++]=w; visited[w]=1; } } } printf(" %d",queue[front++]); if(front==rear) break; v=queue[front]; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值