广度优先遍历

广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶点时,依次遍历其所有的邻接点,然后再从这些邻接点出发,同样依次访问它们的邻接点。按照此过程,直到图中所有被访问过的顶点的邻接点都被访问到。

最后还需要做的操作就是查看图中是否存在尚未被访问的顶点,若有,则以该顶点为起始点,重复上述遍历的过程。

广度优先搜索的实现需要借助队列这一特殊数据结构,实现代码为:

#include 
#include 
#include 

#define MAX_VERTEX_NUM 20//顶点最大数
#define VRType int//顶点间关系变量类型
#define InfoType char//存储弧额外信息的变量类型
#define VertexType int//顶点数据类型
bool visited[MAX_VERTEX_NUM];//辅助数组,记录是否被访问过
typedef struct Queue
{
    VertexType data;
    struct Queue *next;
}Queue;
typedef struct 
{
    VRType adj;
    InfoType info;
}ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct 
{
    VertexType vexs[MAX_VERTEX_NUM];
    AdjMatrix arcs;
    int vexnum,arcnum;
}MGgraph;

int LocateVex(MGgraph *G,VertexType v)
{
    int i=0;
    for(;ivexnum;i++)
    {
        if(G->vexs[i]==v)
        {
            break;
        }
    }
    if(i>=G->vexnum)
    {
        printf("不存在这个顶点\n");
        return -1;
    }
    return i;
}

void CreateUDG(MGgraph *G)
{
    scanf("%d%d",&(G->vexnum),&(G->arcnum));
    for(int i=0;ivexnum;i++)
    {
        scanf("%d",&(G->vexs[i]));
    }
    for(int i=0;ivexnum;i++)
    {
        for(int j=0;jvexnum;j++)
        {
            G->arcs[i][j].adj=0;
            G->arcs[i][j].info=NULL;
        }
    }
    for(int k=0;karcnum;k++)
    {
        int v1,v2;
        int i=LocateVex(G,v1);
        int j=LocateVex(G,v2);
        if(i==-1||j==-1)
        {
            printf("没有找到此顶点\n");
            return;
        }
        G->arcs[i][j].adj=1;
        G->arcs[j][i].adj=1;
    }
}

int FirstAdjVex(MGgraph G,int v)
{
    for(int i=0;inext=NULL;
}
//顶点元素v进队列
void EnQueue(Queue **Q,VertexType v)
{
    Queue *element=(Queue*)malloc(sizeof(Queue));
    element->data=v;
    element->next=NULL;
    Queue *temp=(*Q);
    while(temp->next!=NULL)
    {
        temp=temp->next;
    }
    temp->next=element;
}
//队头元素出队列
void DeQueue(Queue **Q,int *u)
{
    *u=(*Q)->next->data;
    (*Q)->next=(*Q)->next->next;
}
//判断队列是否为空
bool QueueEmpty(Queue *Q)
{
    if(Q->next==NULL)
    {
        return true;
    }
    return false;
}

//BFS
void BFSTraverse(MGgraph G)
{
    int v;
    for(v=0;v=0;w=NextAdjVex(G,u))
                {
                    if(!visited[w])
                    {
                        visited[w]=true;
                        visitVex(G,w);
                        EnQueue(&Q,G.vexs[w]);
                    }
                }
            }
        }
    }
}

int main()
{
    MGgraph G;
    CreateUDG(&G);
    BFSTraverse(G);
    return 0;
}

你可能感兴趣的:(数据结构)