图的广度搜索bfs,邻接表实现

本文介绍了一种使用邻接表表示图的数据结构,并实现了基于该表示的广度优先搜索算法。文中详细解释了如何创建邻接表、插入节点以及进行广度优先搜索遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是邻接表实现的图的广度搜索

邻接表的声明:

struct Node{
    char data;
    int weight;
    Node *next;
};

struct Graph {
    int vertnum;
    Node *AdjList;
};

Graph MGraph;

建立邻接表:

int getNum( Graph *G,char x){
    int i=0;
    for( i=0;i<G->vertnum;i++){
        if(G->AdjList[i].data==x) {
                break;
        }
    }
    return i;
}

void InsertList(Graph *G,char x,char y){
    int j=getNum(G,x);
    Node *p=&(G->AdjList[j]);
    while(p->next){
        if(p->next->data >y) break;
        p=p->next;
    }

    Node *tmp=new Node;
    tmp->data=y;
    tmp->next=p->next;
    p->next=tmp;
}

void mycreate(Graph *G){

    int i,num;
    char x,y;
    char tmp;
    cin>>num;
    G->vertnum=num;
    G->AdjList=new Node[num];
    for(i=0;i<G->vertnum;i++){
        cin>>x;
        G->AdjList[i].data=x;
        G->AdjList[i].next=NULL;
    }
    cin>>num;
    for(i=0;i<num;i++){
        char tmp;
        cin>>x>>y;
       InsertList(G,x,y);
       InsertList(G,y,x);
    }
}

输出建立后的邻接表:

void showGraph(Graph *G){

    int i;
    Node *p;
    for(i=0;i<G->vertnum;i++){
        cout<<G->AdjList[i].data<<":";
        p=G->AdjList[i].next;
        while(p){
            cout<<" -> "<<p->data;
            p=p->next;
        }
        cout<<"^"<<endl;
    }
}

bfs遍历:

void bfs(Graph *G,char x){

    add(x);
    cout<<x;
    vis[x]=1;
    while(!isempty()){
        del(x);
        int ix=getNum(G,x);
       Node *p= &G->AdjList[ix];
        while(p->next){
            char tmp=p->next->data;
            if(!vis[tmp]){
                cout<<" "<<tmp;
                add(tmp);
                vis[tmp]=1;
            }
            p=p->next;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值