图广度优先搜素BFS(邻接表)C/C++

#include <bits/stdc++.h>
using namespace std;

typedef char VertexType;
typedef int EdgeType;
typedef struct EdgeNode{
    int adjvex;
    int weight;
    EdgeNode *nextedge;
}EdgeNode;

typedef struct VNode{
    int visited;
    VertexType data;
    EdgeNode *firstedge;
}VNode;

struct ALGraphStruct{
    VNode vexs[100];
    int vertexnum;
    int edgenum;
}; 

typedef struct ALGraphStruct *ALGraph;

ALGraph CreateALGraph()
{
    ALGraph g=(ALGraph)malloc(sizeof(struct ALGraphStruct));
    g->vertexnum=0;
    g->edgenum=0;
    return g; 
}

void BFS(ALGraph g,int k)
{
    queue <int> q;
    q.push(k);
    g->vexs[k].visited=1;
    int i;
    while(!q.empty()){
        i=q.front();
        q.pop();
        for(EdgeNode *p=g->vexs[i].firstedge;p!=NULL;p=p->nextedge){
            if(g->vexs[p->adjvex].visited==0){
                q.push(p->adjvex);
                g->vexs[p->adjvex].visited=1;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/linyuan703/article/details/81288361