初级BFS

输入:n个顶点,m条边。

接下来输入每一条边的两个顶点。

输出遍历的顺序

#include<iostream>
#include<queue>
bool book[100];//bool mark[100];
int t[500][500];//int ljjz[500][500];
using namespace std;
int n,m;

int main()
{
    int x,y;
    int u;
    cin>>n>>m;
    for(int i=0;i<m;i++){
        cin>>x>>y;
        t[x][y]=t[y][x]=1;
    }
    queue<int>q;
    q.push(1);//将一号顶点压入队列
    book[1]=true;//标记一号顶点已被访问
    cout<<1<<endl;//输出访问的顶点
    while(!q.empty()){//当队列不为空进行循环
        u=q.front();//u是队首元素
        for(int i=1;i<=n;i++){//遍历每一个顶点
            if(!book[i]&&t[u][i]){//如果该顶点与当前顶点u之间有边且未被访问过
                cout<<i<<endl;//输出访问到的顶点
                book[i]=1;//标记它已经被访问过了
                q.push(i);//将此点推入队列
            }
        }
        q.pop();//顶点u出队
    }
}

猜你喜欢

转载自www.cnblogs.com/ZGQblogs/p/9074669.html
BFS
今日推荐