图的广度优先遍历bfs 数组及邻接表实现

广度优先遍历

数组bfs

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int vexs[10];
int arcs[10][10];
int vnum;
}MGraph;
int visit[10]={0};
void  creatAdjmatrix(MGraph &g){
int n,i,j;

cin>>n;
g.vnum=n;
for(i=1;i<=n;i++){
    g.vexs[i]=i;
     for(j=1;j<=n;j++){
    g.arcs[i][j]=0;
}
}

cin>>i>>j;
while(i!=0&&j!=0){
    g.arcs[i][j]=1;
    g.arcs[j][i]=1;
    cin>>i>>j;
}

}
void bfs(MGraph g,int v){
   int myqueue[10];
   int rear=0,front=0;
   myqueue[rear++]=v;
    visit[v]=1;
   while(rear!=front){

    int getfront=myqueue[front++];
    cout<<getfront<<" ";

    for(int i=1;i<=g.vnum;i++){
        if(g.arcs[getfront][i]==1&&visit[i]==0){
            myqueue[rear++]=i;
            visit[i]=1;
        }
    }

   }
}
int main()
{
    MGraph g;
    creatAdjmatrix(g);//5 1 2 1 3 2 5 2 4 0 0//5 1 2 1 3 1 4 3 4 4 2 5 2 5 3 0 0
    bfs(g,1);
    return 0;
}

邻接表bfs

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
 int adjvex;
 struct node *next;
}arcnode;
typedef struct vnode{
 int data;
 arcnode *firstarc;
}vernode;
int visit[10];
void creatadjlist(vernode g[]){ //5  1 2  1 3  2 5  2 4  2 3  0 0
int n,i,j;
cin>>n;
for(i=1;i<=n;i++){
    g[i].data=i;
    g[i].firstarc=NULL;
}
cin>>i>>j;
while(i!=0&&j!=0){
    arcnode *p;
    p=new arcnode;
    p->adjvex=j;
    p->next=g[i].firstarc;
    g[i].firstarc=p;
    cin>>i>>j;
}
}
void dfs(vernode g[],int v){
vernode queue[10];
int rear=0,front=0;
queue[rear++]=g[v];
visit[v]=1;

while(rear!=front){
    vernode p=queue[front++];
    cout<<p.data<<" ";
    arcnode *q=p.firstarc;
    while(q!=NULL){
            if(visit[q->adjvex]==0){
        queue[rear++]=g[q->adjvex];
        visit[q->adjvex]=1;
            }

        q=q->next;
    }

}

}

int main()
{
    vernode g[10];
    creatadjlist(g);
    //cout<<g[1].firstarc->next->adjvex;
    dfs(g,1);
    //5 1 2 1 3 2 5 2 4 2 3 0 0//6 1 4 1 5 1 2 2 5 2 3 3 6 4 3 4 6 4 4 0 0
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值