图的广度优先遍历邻接矩阵

#include <iostream>

using namespace std;

const int INF = 9999;

int main()
{
    int i,j,n,m,a,b,cur,book[101] = {0},e[101][101];
    int qu[101],tail,head;
    cin>>n>>m;
    //初始化二维矩阵
    for(i = 1;i <= n;i++)
    {
        for(j = 1;j <= n;j++)
        {
            if(i == j)
            {
                e[i][j] = 0;
            }
            else
            {
                e[i][j] = INF;
            }
        }
    }
    //读入顶点之间的边
    for(i = 1;i <= m;i++)
    {
        cin>>a>>b;
        e[a][b] = 1;
        e[b][a] = 1;
    }
    //队列初始化
    head = 1;
    tail = 1;
    //从1号顶点出发,将1号队列加入队列
    qu[tail] =  1;
    tail++;
    book[1] = 1;
    //当队列不为空的时候循环
    while(head < tail)
    {
        cur = qu[head];
        for(i = 1;i <= n;i++)
        {
            if(e[cur][i] == 1 && book[i] == 0)
            {
                qu[tail] = i;
                tail++;
                book[i] = 1;
            }
        }
        //如果tail大于n,则表明所有的顶点已经被访问过了
        if(tail > n)
        {
            break;
        }
        head++;
    }
    for(i = 1;i < tail;i++)
    {
        cout<<qu[i]<<" ";
    }
    cout<<endl;
    return 0;
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/u012967763/article/details/52013270
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞