图的广度优先搜索(采用邻接表存储方式)

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20

int visited[MAXSIZE];

typedef struct node{
    int adjvex;
    struct node * next;
}Node;

typedef struct{
    int vertex;
    Node * first;
}VNode;

typedef struct qnode{
    int data;
    struct qnode * next;
}Qnode;

typedef struct{
    Qnode * front;
    Qnode * rear;
}LinkQueue;

LinkQueue * init(){             //初始化队列
    LinkQueue * lq;
    Qnode * qn;
    qn = (Qnode *)malloc(sizeof(Qnode));
    lq = (LinkQueue *)malloc(sizeof(LinkQueue));

    qn->next = NULL;
    lq->front = qn;
    lq->rear = qn;
    return lq;
}

void inLinkQueue(LinkQueue * lq,int x){           //入队
    Qnode * p = (Qnode *)malloc(sizeof(Qnode));
    p->data = x;
    p->next = NULL;
    lq->rear->next = p;
    lq->rear = p;
}

int outLinkQueue(LinkQueue * lq){           //出队
    Qnode * p;
    int x;
    if(lq->front == lq->rear){
        printf("队列为空\n");
        return -1;
    }else{
        p = lq->front->next;
        x = p->data;
        lq->front->next = p->next;
        free(p);
        if(lq->front->next == NULL){
            lq->rear = lq->front;
        }
        return x;
    }
}

void create(VNode g[],int n,int e){         //创建无向图的邻接表
    Node * p;
    int i,j;

    for(int t=0;t<n;t++){
        g[t].vertex = t;
        g[t].first = NULL;
    }

    for(int k=0;k<e;k++){
        printf("请输入连通边i->j\n");
        scanf("%d,%d",&i,&j);
        p = (Node *)malloc(sizeof(Node));
        p->adjvex = j;
        p->next = g[i].first;
        g[i].first = p;
        p = (Node *)malloc(sizeof(Node));
        p->adjvex = i;
        p->next = g[j].first;
        g[j].first = p;
    }
}

void BFS(VNode g[]){                        //广度优先搜索
    LinkQueue * lq = init();
    Node * p;
    int j;
    printf("%4d",g[0].vertex);
    visited[0] = 1;
    inLinkQueue(lq,0);
    while(lq->front != lq->rear){
        j = outLinkQueue(lq);
        p = g[j].first;
        while(p != NULL){
            if(!visited[p->adjvex]){
                printf("%4d",g[p->adjvex].vertex);
                inLinkQueue(lq,p->adjvex);
                visited[p->adjvex] = 1;
            }else{
                p = p->next;
            }
        }
    }
}

int main(){
    VNode g[MAXSIZE];
    int n,e;
    printf("请输入节点的个数!\n");
    scanf("%d",&n);
    printf("请输入边的个数\n");
    scanf("%d",&e);
    create(g,n,e);
    printf("广度优先搜索结果:\n");
    BFS(g);
    return 0;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caoyahong114/article/details/51558621
个人分类: 数据结构
上一篇CPU核心温度获取
下一篇Linux的基本知识(1)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭