图的广度优先遍历(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;
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值