PTA List Components

时间:2021-08-29 22:47:20

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 5

Sample Output:

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

这题比较水……就是写个图的DFS和BFS……当然DFS是遍历到这个点才标记该点已经被访问,并且已经访问过的点就不要再去访问了,不然如果图中有环的话就一直递归下去了,BFS的话是只要入队就把相应节点标记(不用管它有没有遍历到,因为只要入队肯定会遍历到),这样标记过的点就不用再入队了,从而避免了重复入队的发生。

下面是代码:

//
//  main.c
//  List Components
//
//  Created by 余南龙 on 2016/12/6.
//  Copyright © 2016年 余南龙. All rights reserved.
//

#include <stdio.h>
#include <string.h>

#define MAXV 10000
int Graph[MAXV][MAXV];
int visit[MAXV], connected[MAXV];
int N, E, top;

void DFS(int v){
    int i;

    connected[++top] = v;
    visit[v] = ;
    ; i < N; i++){
         == Graph[v][i]&& == visit[i]){
            DFS(i);
        }
    }
}

void BFS(int v){
    ];
    , j = , i;

    Q[++tail] = v;
    visit[Q[j]] = ;
    ){
        connected[++top] = Q[j];
        ; i < N; i++){
             == Graph[Q[j]][i]&& == visit[i]){
                Q[++tail] = i;
                visit[i] = ;
            }
        }
        j++;
        if(tail < j){
            break;
        }
    }
}

void Init(){
    int i, u, v;

    scanf("%d%d", &N, &E);
    ; i < E; i++){
        scanf("%d%d", &u, &v);
        Graph[u][v] = Graph[v][u] = ;
    }
}

void Output(){
    int i;

    printf("{ ");
    ; i <= top; i++){
        printf("%d ", connected[i]);
    }
    printf("}\n");
}

int main(){
    int j;
    Init();
    memset(visit, , MAXV * sizeof(int));
    top = -;
    ; j < N; j++){
         == visit[j]){
            DFS(j);
            Output();
            top = -;
        }
    }
    memset(visit, , MAXV * sizeof(int));
    top = -;
    ; j < N; j++){
         == visit[j]){
            BFS(j);
            Output();
            top = -;
        }
    }
    ;
}