(optional) Connected Components
Time limit: 5000ms
Memory limit: 256mb
Description:
This is an optional problem. You won't lose any mark if you skip it.
In this exercise, the undirected graph may not be connected and you are required to compute the number of connected components.
You can compute it using DFS or BFS starting from any node.
The main function has been provided. It first asks the user to input the total number of edges m, and input all these edges to construct the adjacency list. Then you may use the conNum function to find the number of connected components.
In this conNum function, you can use DFS or BFS traversal. From one unvisited node, traverse this component. And then from another unvisited node, traverse the second component until all nodes are visited. We consider that a single node with no edges does not appear in the graph. So in this exercise, a single node is not a component.
Sample Input 1:
0
Sample Output 1:
Input the number of edges:
Input these edges:
0
Sample Input 2:
7
0 2
1 3
4 5
6 5
7 6
1 0
Sample Output 2:
Input the number of edges:
Input these edges:
2
Hint:
You may need to copy the function you write from ex1 or ex2. You could design and implement it as you like.
Code Template:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100
typedef struct _adjlist {
int node;
struct _adjlist *link;
} adjlist;
adjlist graph[MAX_NODES];
int visited[MAX_NODES]; // 0-unvisited 1-visited
void insert(int v1, int v2)
{
/*
insert edge (v1,v2) into adajacency list.
Fill in your code here...
*/
}
int conNum()
{
/*
Fill in your code here...
visit an unvisited node to obtain a new conneted component, until all nodes are visited.
*/
}
int main()
{
int m,a,b;
// initialize
for(int i=0;i<MAX_NODES;i++)
{
graph[i].link=NULL;
visited[i]=0; // unvisited
}
printf("Input the number of edges:\n");
scanf("%d",&m);
printf("Input these edges:\n");
for(int i=0; i<m; i++)
{
scanf("%d %d", &a, &b);
insert(a,b);
insert(b,a);
}
int num=conNum();
printf("%d",num);
return 0;
}
Submit