• 数据结构之 图论---bfs(邻接表)


    数据结构实验之图论二:基于邻接表的广度优先搜索遍历

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

    给定一个无向连通图,顶点编号从0到n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)

    输入

    输入第一行为整数n(0< n <100),表示数据的组数。
    对于每组数据,第一行是三个整数k,m,t(0<k<100,0<m<(k-1)*k/2,0< t<k),表示有m条边,k个顶点,t为遍历的起始顶点。
    下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。

    输出

    输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。

    示例输入

    1
    6 7 0
    0 3
    0 4
    1 4
    1 5
    2 3
    2 4
    3 5

    示例输出

    0 3 4 2 5 1 

    代码:
    #include <iostream>
    #include <string>
    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    #include <queue>;
    
    using namespace std;
    
    struct node
    {
        int data;
        int next;
    }a[6000];
    
    int cnt;
    int head[101];
    void Insert_edge(int u, int v)
    {
        a[cnt].data=u;
        a[cnt].next=head[v];
        head[v]=cnt++;
    }
    
    int list[101],e;
    void bfs(int n, int s) //n个点, s是起点
    {
        queue<int>q;
        bool vis[101];
        memset(vis, false, sizeof(vis));
        q.push(s);
        vis[s]=true;
        int i, dd; //当前队首元素
        int ff;
    
        while(!q.empty())
        {
            dd=q.front();
            q.pop();
            list[e++]=dd;
            int w[101], p=0;
            //queue<int>p;
            for(i=head[dd]; i!=-1; i=a[i].next )
            {
                ff=a[i].data;
                if(vis[ff]==false)
                {
                    //p.push(ff);
                    w[p++]=ff;
                    vis[ff]=true;
                }
            }
            sort(w, w+p); //排序 为了保证大小顺序
            for(i=0; i<p; i++)
            {
               q.push(w[i]);  //遍历结果加入队列
            }
        }
        while(!q.empty())
        {
            ff=q.front();
            q.pop();
            list[e++]=ff;
        }
    }
    
    int main()
    {
        int t;
        cin>>t;
        int i, j;
        int n, m, u, v;
        int start;
    
        while(t--)
        {
            cin>>n>>m>>start;
            cnt=0;
            memset(head, -1, sizeof(head));
            for(i=0; i<m; i++)
            {
                cin>>u>>v;
                Insert_edge(u, v);
                Insert_edge(v, u); //无向图插入边
            }
            bfs(n, start);
            for(i=0; i<e; i++)
            {
                if(i==0)
                  cout<<list[i];
                else
                  cout<<" "<<list[i];
            }
            cout<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    links[v1]
    WebSocket handshake: Unexpected response code: 404
    Spring mvc 启动 和 请求分发
    匹配括号
    js parseFloat 精度问题
    遍历查找跳格子逻辑
    Generic type test java
    java高效判断素数
    从数组中取3个数全排列
    vue-cli
  • 原文地址:https://www.cnblogs.com/yspworld/p/4122689.html
Copyright © 2020-2023  润新知