BFS

来源:互联网 发布:中国照相馆 知乎 编辑:程序博客网 时间:2024/05/21 09:13

图的广度优先搜索遍历类似于二叉树的层次遍历

#define MAXSIZE 100typedef struct ArcNode{    int adjvex;    struct ArcNode *nextarc;    int info;}ArcNode;typedef struct VNode{    char data;    ArcNode *firstarc;}typedef struct {    VNode adjlist[MAXSIZE];    int n,e;}AGraph;typedef enum{TRUE,FALSE}BOOLEAN;BOOLEAN visited[MAXSIZE];/*访问标记数组*/typedef struct Queue{    int data[MAXSIZE];    int front,rear;}Queue;/*BFS的特性决定它要用到队列*/void BFS(AGraph *G){    ArcNode *p;    int w;    Queue *Q;    Q=new Queue;    Q->front = Q->rear =0;    for(int n=0;n<G->n;n++)        visited[n]=FALSE;    for(int n=0;n<G->n;n++)    {        v=G->adjlist[n].data;        if(!visited[v])        {            Q->data[++Q->rear]=v;            while(Q->front != Q->rear)            {                w = Q->data[++front];//入队                visited[w]=TRUE;                visit(w);//置访问标记并出对                p=G->adjlist[w].firstarc;                while(p != NULL)//将与w相邻的所有结点入队                {                    if(!visit[p->adjvex])                        Q->data[++rear]=p->adjvex;                    p=p->nextarc;                }            }//end while        }//end if     }//end for}
0 0