采用邻接矩阵实现无向图的广度遍历

《采用邻接矩阵实现无向图的广度遍历》

#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#define MVNum 100
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT  10

#define MAXQSIZE 100
using namespace std;
typedef  int QElemType;
typedef struct {
    QElemType data[MAXQSIZE];
    int front,rear;
} SqQueue;

//初始化队列
void InitQueue(SqQueue &Q) {
    Q.front = Q.rear = 0;
}

//判队列是否为空
int isEmpty(SqQueue &Q) {
    if (Q.rear == Q.front) return 1;
    return 0;
}

//入队
int EnQueue(SqQueue &Q, QElemType e) {
    if ((Q.rear+1)%MAXQSIZE == Q.front) {
        printf(“队列已满,不能加入新元素!\n”);
        return 0;
    }
    Q.data[Q.rear] = e;
    Q.rear = (Q.rear+1)%MAXQSIZE;
    return 1;
}

//出队
int DeQueue(SqQueue &Q, QElemType &e) {
    if (isEmpty(Q)) {
        printf(“队列为空,,没有元素!\n”);
        return 0;
    }
    e = Q.data[Q.front];
    Q.front = (Q.front+1)%MAXQSIZE;
    return 1;
}

bool visited[MVNum];
typedef string VerTexType;
typedef struct ArcNode {
    int adjvex;
    struct ArcNode *nextarc;
    char info;
} ArcNode;
typedef struct VNode {
    VerTexType data;
    ArcNode *firstarc;
} VNode,AdjList[MVNum];
typedef struct {
    AdjList vertices;
    int vexnum,arcnum;
} ALGraph;
int LocateVex(ALGraph G,VNode v) {
    int i;
    for(i=0; i<G.vexnum; i++) {
        if(G.vertices[i].data==v.data)
            break;
    }
    if(i<G.vexnum)
        return i;
    else {
        cout<<“cuowu”;
        return 0;
    }

}
int CreateUDG(ALGraph &G) {
    int i,j,k;
    VNode v1,v2;
    cin>>G.vexnum>>G.arcnum;
    for(i=0; i<G.vexnum; i++) {
        cin>>G.vertices[i].data;
        G.vertices[i].firstarc=NULL;
    }
    for(k=0; k<G.arcnum; ++k) {
        cin>>v1.data>>v2.data;
        i=LocateVex(G,v1);
        j=LocateVex(G,v2);
        ArcNode* p1=new ArcNode;
        ArcNode* p2=new ArcNode;
        p1->adjvex=j;
        p1->nextarc=G.vertices[i].firstarc;
        G.vertices[i].firstarc=p1;
        p2->adjvex=i;
        p2->nextarc=G.vertices[j].firstarc;
        G.vertices[j].firstarc=p2;
    }
    return 1;

}

void BFS(ALGraph G,int v) {
    ArcNode *w;//此处注意不需要再分配空间
    // for(int i=0;i<MVNum;i++)
    //visited[v]=false;
    cout<<G.vertices[v].data<< ” ” ;
    visited[v]=true;
    SqQueue Q;
    InitQueue(Q);
    EnQueue(Q,v);
    while(!isEmpty(Q)) {
        DeQueue(Q,v);
        for(w=G.vertices[v].firstarc; w!=NULL; w=w->nextarc)
            if(!visited[w->adjvex]) {
                cout<<G.vertices[w->adjvex].data<<” “;
                visited[w->adjvex]=true;
                EnQueue(Q,w->adjvex);
            }
    }
}
void BFSTraverse(ALGraph G) {
    int v;
    for (v=0; v<G.vexnum; ++v)
        visited[v]=false;
    for(v=0; v<G.vexnum; v++)
        if(!visited[v])
            BFS(G,v);
}
int main() {
    ALGraph G;
    CreateUDG(G);
    BFSTraverse(G);
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/zhaojinmiao/article/details/80676483
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞