图的广度优先遍历(BFS)

图的广度优先遍历类似于树的层次遍历,差异在于需要判断该顶点是否已经被访问。


//邻接表
typedef struct ArcNode{
     
    int adjvex;
    struct ArcNode* nextArc;
}ArcNode;

typedef struct{
     
    char data;
    ArcNode* firstArc;
}VNode;

typedef struct{
     
    VNode adjList[MaxSize];
    int n;
    int e;
}AGraph;

int visit[MaxSize];

void initAGraph(AGraph* &G){
     
    G->e = 3;
    G->n = 3;
    cout<<"data:"<<endl;
    for (int i = 0; i < G->n; i++) {
     
        cin>>G->adjList[i].data;
        G->adjList[i].firstArc = NULL;
    }
    cout<<"vi,vj"<<endl;
    for (int j = 0; j < G->e; j++) {
     
        int vi,vj;
        cin>>vi>>vj;
        ArcNode* node = new ArcNode();
        node->adjvex = vj;
        node->nextArc = G->adjList[vi].firstArc;
        G->adjList[vi].firstArc = node;
    }
}

void Travase(VNode vnode){
     
    cout<<"current: "<<vnode.data<<endl;
}

void BFS(AGraph* G,int v){
     
    ArcNode* p;
    int que[MaxSize],front = 0,rear = 0;
    int j;
    Travase(G->adjList[v]);
    visit[v] = 1;
    rear = (rear+1)%MaxSize;
    que[rear] = v;
    while (front != rear) {
     
        front = (front + 1)%MaxSize;
        j = que[front];
        p = G->adjList[j].firstArc;
        while (p != NULL) {
     
            if (visit[p->adjvex] == 0) {
     
                Travase(G->adjList[p->adjvex]);
                visit[p->adjvex] = 1;
                rear = (rear+1)%MaxSize;
                que[rear] = p->adjvex;
            }
            p = p->nextArc;
        }
    }
}

int main(int argc, const char * argv[]) {
     
    AGraph* G = new AGraph();
    initAGraph(G);
    //遍历连通图,对于非连通图,只需遍历所有顶点即可
    BFS(G, 0);
    return 0;
}

你可能感兴趣的:(数据结构和算法,数据结构,bfs)