码迷,mamicode.com
首页 > 其他好文 > 详细

BFS广度优先遍历

时间:2015-06-03 17:34:30      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

队列实现广度优先遍历

#include <iostream>
#include <queue>
using namespace std;

int  visit[5]={0};

typedef struct {
        char vexs[5];
        int AdjMatrix[5][5];
        int vexnum;
        }Graph;

Graph g={
    {a,b,c,d,e},
      {
       0,1,0,1,0,
       1,0,1,0,1,
       0,0,0,1,1,
       1,0,0,0,0,
       0,1,1,0,0
      } ,
      5
      };

 queue<int> list;;


int BFS(Graph *g,int nowVex){

    if(visit[nowVex]==0)
    cout<<"visit "<<g->vexs[nowVex]<<" ";
    visit[nowVex]=1;

    if(list.size()!=0)
    list.pop();
    for(int i=0;i<g->vexnum;i++)
    {
        if(g->AdjMatrix[nowVex][i]==1&&visit[i]==0)
        {
            list.push(i);
        //    cout<<"nowVex "<<nowVex<<" push "<<g->vexs[i]<<endl;
        }
    }

    while(list.size()!=0){
         //  cout<<" list front is "<<g->vexs[list.front()]<<endl;
           BFS(g,list.front());
    }
    return 0;
}


int main()
{
    BFS(&g,0);
}

 

BFS广度优先遍历

标签:

原文地址:http://www.cnblogs.com/lxdonge/p/4549417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!