c++ 广度优先搜索

#include <iostream>
using namespace std;

const int verMax=9;
const int queMax=10; // >=9皆可

struct node//声明图形顶点结构
{
int vertex;
struct node *next;
};

typedef struct node *graph;
struct node head[verMax];//声明顶点结构数组
int que[queMax];
int front=-1;
int rear=-1;
int visit[verMax];//查找记录//队列的存入

int enque(int v)
{
    if(rear>=queMax)//队列已满
    return -1;
else
{
    rear++;//对了尾端指针后移
    que[rear]=v;//将值存入队列中
    return 1;
    }
}
//队列的取出
int deque()
{
    if(front==rear)//队列已空
        return -1;
    else
    {
        front++;
        return que[front];
    }
}
//广度优先搜索法
void BFS(int v)
{
    graph point;
    enque(v);//存入队列
    visit[v]=1;//已查找
    cout<<"["<<v<<"]==>";
    while(front!=rear)
    {
        v=deque();
        point=head[v].next;
        while(point!=NULL)//读入邻接列表所有顶点
        {
            if(visit[point->vertex]==0)
            {
                enque(point->vertex);//存入队列
                visit[point->vertex]=1;//已查找过的顶点
                cout<<"["<<point->vertex<<"]==>";
            }
            point=point->next;
        }
    }
}
//建立邻接顶点至邻接列表内
void create_graph(int v1,int v2)
{
    graph point,New;
    New=(graph)malloc(sizeof(struct node));
    if(New!=NULL)
    {
        New->vertex=v2;//邻近顶点
        New->next=NULL;
        point=&(head[v1]);
        while(point->next!=NULL)
            point=point->next;
        point->next=New;//串连在列表尾端
    }
}
//输出邻接列表内数据
void print_graph(struct node *head)
{
    graph point;
    point=head->next;//设置point为首节点
    while(point!=NULL)
    {
        cout<<"["<<point->vertex<<"] ";
        point=point->next;
    }
    cout<<endl;
}
//主程序
void main()
{
    int node[20][2]={
    {1,2},{2,1},{1,3},{3,1},{2,4},{4,2},{2,5},{5,2},{3,6},{6,3},
    {3,7},{7,3},{4,8},{8,4},{5,8},{8,5},{6,8},{8,6},{7,8},{8,7}};
    int i;
    for(i=0;i<verMax;i++)
    {
        head[i].vertex=i;
        head[i].next=NULL;
    } 
    for(i=0;i<verMax;i++)
        visit[i]=0;

    for(i=0;i<20;i++)
        create_graph(node[i][0],node[i][1]);

    cout<<"======Graph======"<<endl;
    for(i=1;i<verMax;i++)
    {
        cout<<"Vertex["<<i<<"]: ";
        print_graph(&head[i]);
    } 
    //广度优先搜索
    cout<<"Bradth-First-Search:"<<endl<<"&BEGIN==>";
    BFS(4);
    cout<<"END&"<<endl;
}
posted @ 2020-01-09 13:23  创新创造学习整合套路  阅读(634)  评论(0编辑  收藏  举报