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

BFS - 广度优先搜索 - 邻接列表表示法

时间:2017-07-26 00:13:36      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:pac   poi   else   str   引入   span   clu   ons   name   

2017-07-25 21:40:22

writer:pprp

在DFS的基础上加上了一个BFS函数

#include <iostream>
#include <queue>

using namespace std;

const int N = 9;

queue<int> qu;

int visited[N] = {0};    //新引入一个数组,用于标记是否访问过

struct node
{
    int vertex;
    node*next;
};

node head[N];

void BFS(int vertex)              // 宽度优先搜素
{
      node*point;
      qu.push(vertex);
      visited[vertex] = 1;
      cout<< vertex <<"->";
      while(!qu.empty())
      {
            vertex = qu.front();
            qu.pop();
            point = head[vertex].next;
            while(point!=NULL)
            {
                  if(visited[point->vertex] == 0)
                  {
                        qu.push(point->vertex);
                        visited[point->vertex] = 1;
                        cout <<point->vertex<<"->";
                  }
                  point = point->next;
            }
      }
}

void create(int val1,int val2)
{
    node*point;
    node*nnew = new node();
    nnew->vertex = val2;
    nnew->next = NULL;
    point = &head[val1];
    while(point->next!=NULL)
    {
        point = point->next;
    }
    point->next = nnew;
}


void print()
{
    node*point;
    for(int i = 0; i < N; i++)
    {
        point = head[i].next;
        cout << "Head["<<i<<"]";
        while(point!=NULL)
        {
            cout <<"-> "<<point->vertex;
            point = point->next;
        }
        cout << endl;
    }
}

int main()
{
    int node1,node2;
    
    for(int i = 0; i < N; i++)
    {
        head[i].vertex = i;
        head[i].next = NULL;
    }
    while(1)
    {
        cout <<"please enter the start point" << endl;

        cin >> node1;
        if(node1 == -1)
            break;
        cout <<"please enter the end point" << endl;
        cin >> node2;

        if(node1 == node2)
            cout <<"自身循环"<<endl;
        else if(node1>=N||node2>=N)
            cout <<"超出范围"<<endl;
        else
            create(node1,node2);
    }

    cout << "邻接表为:" << endl;
    print();
    

    
    cout <<"\n"<<endl;
    
    cout <<"BFS: "<<endl;
    
    BFS(1);

    return 0;
}

 

BFS - 广度优先搜索 - 邻接列表表示法

标签:pac   poi   else   str   引入   span   clu   ons   name   

原文地址:http://www.cnblogs.com/ilovelianghui/p/7236735.html

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