2141-数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历

来源:互联网 发布:收银台软件 编辑:程序博客网 时间:2024/06/06 14:23
#include <iostream>#include <cmath>#include <cstdlib>#include <queue>#include <cstring>using namespace std;int map[1123][1123]; ///储存邻接表int vis[1123]; /// 标记节点是否已访问int ans[1123]; /// 储存遍历序列int p;void bfs(int k, int n){    p = 0;    queue<int>Q;    vis[k] = 1;    ans[p++] = k; /// 将起点放入遍历序列    Q.push(k);    while(!Q.empty())    {        int x = Q.front();        Q.pop();        for(int i = 0; i < n; i++)        {            if(!vis[i] && map[x][i]) /// 如果两点相连并且未访问过            {                vis[i] = 1;                ans[p++] = i;                Q.push(i);            }        }    }    //cout << p << endl;}int main(){    int t;    int n,m,k;    cin >> t;    while(t--)    {        int u,w; /// 节点        cin >> n >> m >> k;        memset(map, 0 ,sizeof(map));        memset(vis, 0, sizeof(vis));        while(m--)        {            cin >> u >> w;            map[u][w] = map[w][u] = 1; /// 此时将邻接表两点赋值为1 表示两点相连        }        bfs(k, n);        //cout << p << endl;        for(int i = 0; i < p; i++)        {            i + 1 == p ? cout << ans[i] << endl : cout << ans[i] << " ";        }    }    return 0;}
阅读全文
0 0
原创粉丝点击