图的遍历——广度优先遍历——邻接表

来源:互联网 发布:网络电视怎么搜台 编辑:程序博客网 时间:2024/06/03 19:21
/*图的遍历——广度优先遍历——邻接表*/#include<stdio.h>#include<stdlib.h>#define MAXSIZE 20#define OK 1#define ERROR 0/*队列的存储结构*/typedef int Status;typedef int QElemtype;typedef struct{    QElemtype data[MAXSIZE];    int front;    int rear;}sqQueue;/*邻接表的存储结构*/#define MAXVEX 100      /*最大顶点数*/typedef char VertexType;     /*顶点*/typedef int EdgeType;   /*权值*/typedef int Boolean;    /*Boolean是布尔类型,其值为TURE和FALSE*/Boolean visited[MAXVEX];    /*访问标志的数组*/typedef struct EdgeNode     /*边表结点*/{    int adjvex;     /*邻接点域,存储该顶点对应的下标*/    EdgeType weight;    /*用于存储权值,对于非网图可以不需要*/    struct EdgeNode * next;     /*链域,指向下一个邻接点*/}EdgeNode;typedef struct VertexNode   /*顶点表结点*/{    VertexType data;    /*顶点表结点*/    EdgeNode * firstedge;   /*边表头指针*/}VertexNode,AdjList[MAXVEX];typedef struct {    AdjList adjList;    int numVertexes,numEdge;    /*图中当前顶点数和边数*/}GraphAdjList;Status InitQueue(sqQueue * Q){    Q->front=0;    Q->rear=0;    return OK;}Status QueueLength(sqQueue Q){    return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;}Status EnQueue(sqQueue * Q, QElemtype e){    if((Q->rear+1)%MAXSIZE==Q->front)    {        return ERROR;    }    Q->data[Q->rear]=e;    Q->rear=(Q->rear+1)%MAXSIZE;    return OK;}Status DeQueue(sqQueue * Q,QElemtype * e){    if(Q->front==Q->rear)    {        return ERROR;    }    *e=Q->data[Q->front];    Q->front=(Q->front+1)%MAXSIZE;    return OK;}/*邻接表的广度遍历算法*/void BFSTraverse(GraphAdjList * GL){    int i;    EdgeNode * P;    sqQueue Q;    for(i=0;i<GL->numVertexes;i++)        visited[i]=false;    InitQueue(&Q);    for(i=0;i<GL->numVertexes;i++)    {        if(!visited[i])        {            visited[i]=true;            printf("%c",GL->adjList[i].data);            EnQueue(&Q,i);            while(QueueLength(Q)!=0)            {                DeQueue(&Q,&i);                P=GL->adjList[i].firstedge;     /*找到当前顶点边表链表头指针*/                while(P)                {                    if(!visited[P->adjvex]) /*若此顶点未被访问*/                    {                        visited[P->adjvex]=true;                        printf("%c",GL->adjList[P->adjvex].data);                        EnQueue(&Q,P->adjvex);  /*将此顶点入队列*/                    }                    P=P->next;  /*将指针指向下一个邻接点*/                }            }        }    }}int main(){    return 0;}
0 0
原创粉丝点击