BFS(广度遍历)

#include <iostream>
#include <queue>
/**
 *DFS usage:Refer to the hype data  structure
 */
using namespace std;
#define  maxvertex   100
typedef  char vertextype;   //vertex
typedef  int Edgetype ;     //edge
//define linklist node
typedef  struct EdgeNode{
    int adjvex ;//adjvex  store the  index of  vertex
    Edgetype  weight;
    struct EdgeNode *next;  //list
}EdgeNode;
//define array  which  can be used to store the vertex
typedef struct  VertexNode{
    vertextype data;
    EdgeNode*  firstedge  ;//Edge pointer
}VertexNode,Adjlist[maxvertex];
//define  grapha  which describe the  numbers of vertex and edge
typedef  struct {
   Adjlist  adjlist;
   int numvertex,numedge;
}GraphAdjlist;
//establish the grapha
void CreateALGrapha(GraphAdjlist *G){
   int i,j,k;
   EdgeNode *e;
   cout<<"input  the  numbers of  vertex and  edge:"<< endl;
   cin>>G->numvertex>>G->numedge;
   cout<<"input the information of vertex"<<endl;
   for(i=0;i<G->numvertex;i++){
       cin>>G->adjlist[i].data;
       G->adjlist[i].firstedge=NULL;
   }
   for(k=0;k<G->numedge;k++){
      //establish
       cout<<"input (Vi,Vj) number:"<<endl;
       cin>> i>>j;
       e=(EdgeNode*)malloc(sizeof(EdgeNode));
       e->adjvex=j;  //index of  adjvex
       e->next=G->adjlist[i].firstedge;
       G->adjlist[i].firstedge=e;
       e=(EdgeNode*)malloc(sizeof(EdgeNode));
       e->adjvex=i;
       e->next=G->adjlist[j].firstedge;
       G->adjlist[j].firstedge=e;
   }
}
typedef  int boollean;
boollean  visited[maxvertex];

void BFSTraverse(GraphAdjlist GL) {
    int i;
    EdgeNode *p;
    queue<int> Q;
    for (i = 0; i < GL.numvertex; i++)
        visited[i] = 0;
    for (i = 0; i < GL.numvertex; i++) {
        if (!visited[i]) {
            visited[i] = 1;
            cout << GL.adjlist[i].data<<" ";//打印顶点,也可以是其他操作
            Q.push(i);
            while (!Q.empty()) {
                i = Q.front();
                Q.pop();
                p = GL.adjlist[i].firstedge;//找到当前顶点边表链表头指针
                while (p) {
                    if (!visited[p->adjvex])//若此顶点未被访问
                    {
                        visited[p->adjvex] = 1;
                        cout << GL.adjlist[p->adjvex].data<<" ";
                        Q.push(p->adjvex);//将此顶点入队列
                    }
                    p = p->next;//指针指向下一个邻接点
                }
            }
        }
    }
}
int main() {
    GraphAdjlist *GL = (GraphAdjlist*)malloc(sizeof(GraphAdjlist));
    CreateALGrapha(GL);
    BFSTraverse(*GL);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值