首页 > 代码库 > 05-图1. List Components (25)
05-图1. List Components (25)
05-图1. List Components (25)
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.
Input Specification:
Each input file contains one test case. For each case, the first line gives two integers N (0<N<=10) 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 "{ v1 v2 ... vk }". 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 5Sample Output:
{ 0 1 4 2 7 } { 3 5 } { 6 } { 0 1 2 7 4 } { 3 5 } { 6 }
#include <stdio.h> void DFS(int graph[][10], int *visited, int v, int n, int *ret) { visited[v] = 1; ret[++ret[0]] = v; for (int i = 0; i < n; ++i) { if (v != i && graph[v][i] && !visited[i]) { DFS(graph, visited, i, n, ret); } } } void BFS(int graph[][10], int *visited, int v, int n) { int queque[20] = {}; int head = 0, rear = 0; queque[rear++] = v; //入队 visited[v] = 1; printf("{ "); while (rear > head) { int curr = queque[head++]; //出队 printf("%d ", curr); for (int i = 0; i < n; ++i) //将每一个每訪问过的邻接节点入队 if (graph[curr][i] && !visited[i]) { visited[i] = 1; queque[rear++] = i; } } printf("}\n"); } int main() { // freopen("test.txt", "r", stdin); int n, edge; scanf("%d%d", &n, &edge); int graph[10][10] = {}; for (int i = 0; i < edge; ++i) { //邻接矩阵方式构造图 int v1, v2; scanf("%d%d", &v1, &v2); graph[v1][v2] = 1; graph[v2][v1] = 1; } int visited[10] = {}; for (int i = 0; i < n; ++i) { int ret[11] = {}; //保存递归遍历到的节点 if (!visited[i]) { DFS(graph, visited, i, n, ret); printf("{ "); for (int j = 1; j <= ret[0]; ++j) { printf("%d ", ret[j]); } printf("}\n"); } } for (int i = 0; i < n; ++i) //重置已訪问标记 visited[i] = 0; for (int i = 0; i < n; ++i) { //BFS if (!visited[i]) { BFS(graph, visited, i, n); } } return 0; }
题目链接:http://www.patest.cn/contests/mooc-ds/05-%E5%9B%BE1
05-图1. List Components (25)