首页 新闻 会员 周边 捐助

列出连通集 DFS和BFS

0
悬赏园豆:30 [待解决问题]

PTA的一道题

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAXN 10

struct Q{
    int Data[MAXN];
    int N, n;
};
typedef struct Q * Queue;

struct E{
    int v1, v2;
    //int weigh  //没有权重
};
typedef struct E *Edge;

struct G{
    int v;
    int e;
    int Matrix[MAXN][MAXN];
};
typedef struct G * Graph;

Graph CreateGraph(int);
void EnGraph(Graph, Edge);
void Print(Graph);
void DFS(Graph, int, int *);
void BFS(Graph, int, int *);

Queue CreateQueue(int);
void EnQueue(Queue, int);
int DeQueue(Queue);

int main()
{
    int i, j, N, E;
    Graph G;
    Edge e;

    scanf("%d %d", &N, &E);
    G = CreateGraph(N);
    e = (Edge)malloc(sizeof(struct E));
    for( i=1; i<=E; ++i ){
        scanf("%d %d", &e->v1, &e->v2);
        EnGraph(G, e);
    }
    Print(G);

    return 0;
}

Graph CreateGraph(int N)
{
    Graph G = (Graph)malloc(sizeof(struct G));

    G->e = 0;
    G->v = N;
    for( int i=0; i<G->v; ++i ){
        for( int j=0; j<G->v; ++j )
            G->Matrix[i][j] = 0;
    }

    return G;
}
void EnGraph(Graph G, Edge E)
{
    G->Matrix[E->v1][E->v2] = 1;
    G->Matrix[E->v2][E->v1] = 1;
    G->e++;
}
void Print(Graph G)
{
    int i;
    int *N = (int *)malloc(sizeof(int)*G->v);
    
    for( i=0; i<G->v; ++i )
        N[i] = 0;
    
    for( i=0; i<G->v; ++i ){
        if( !N[i] ){
            printf("{", i);
            DFS(G, i, N);
            printf(" }\n");
        }
    }
    
    for( i=0; i<G->v; ++i ){
        if( N[i] ){
            printf("{", i);
            BFS(G, i, N);
            printf(" }\n");
        }
    }
}
void DFS(Graph G, int x, int *N)
{
    printf(" %d", x);
    N[x] = 1;
    for( int i=0; i<G->v; ++i ){
        if( G->Matrix[x][i] && !N[i] ){
            DFS(G, i, N);
        }
    }
}
void BFS(Graph G, int x, int *N)
{
    int i, temp;
    Queue Q = CreateQueue(G->v);

    EnQueue(Q, x);
    N[x] = 0;
    printf(" %d", x);
    while( Q->n != -1 ){    //队列空
        temp = DeQueue(Q);
        for(i=0; i<G->v; ++i ){
            if( G->Matrix[temp][i] && N[i] ){
                EnQueue(Q, i);
                N[i] = 0;
                printf(" %d", i);
            }
        }
    }
}
Queue CreateQueue(int x)
{
    Queue Q = (Queue)malloc(sizeof(struct Q));
    Q->N = x;
    Q->n = -1;

    return Q;
}
void EnQueue(Queue Q, int x)
{
    Q->Data[++Q->n] = x;
}

int DeQueue(Queue Q)
{
    return Q->Data[Q->n--];
}

这个测试点一直过不去,求大佬帮忙

り罐罐。的主页 り罐罐。 | 初学一级 | 园豆:46
提问于:2020-03-25 09:48

答主过了吗

啥也不爱的耀 4年前
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册