首页 > 代码库 > BFS - 广度优先搜索 - 邻接列表表示法

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

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 - 广度优先搜索 - 邻接列表表示法