zoukankan      html  css  js  c++  java
  • 1048-图的宽度优先遍历序列

    描述

     

    (graph)是数据结构 G=(V,E),其中VG中结点的有限非空集合,结点的偶对称为边(edge)EG中边的有限集合。设V={0,1,2,……,n-1},图中的结点又称为顶点(vertex),有向图(directed graph)指图中代表边的偶对是有序的,用<uv>代表一条有向边(又称为弧),则u称为该边的始点(尾),v称为边的终点(头)。无向图(undirected graph)指图中代表边的偶对是无序的,在无向图中边(uv )(vu)是同一条边。

    输入边构成无向图,求以顶点0为起点的宽度优先遍历序列。

    输入

     

    第一行为两个整数ne,表示图顶点数和边数。以下e行,每行两个整数,表示一条边的起点、终点,保证不重复、不失败。1≤n≤20,0≤e≤190

    输出

     

    前面n行输出无向图的邻接矩阵,最后一行输出以顶点0为起点的宽度优先遍历序列,对于任一起点,按终点序号从小到大的次序遍历每一条边。每个序号后输出一个空格。

    样例输入

    4 5

    0 1

    0 3

    1 2

    1 3

    2 3

    样例输出

    0 1 0 1

    1 0 1 1

    0 1 0 1

    1 1 1 0

    0 1 3 2

    #include<iostream>
    #include<list>
    using namespace std;
    bool flag[101];
    int temp[101][101];
    
    list<int> S;
    
    void bfs(int k,int n)
    {
        int i,j;
        S.push_back(k);
        while(S.size()>0)
        {
            i=S.front();
            cout<<i<<' ';
            S.pop_front();
            for(j=0;j<n;j++)
            {
                if(temp[i][j]&&!flag[j])
                {
                    temp[i][j]=0;
                    temp[j][i]=0;
                    flag[j]=1;
                    S.push_back(j);
                }
            }
        }
        return;
    }
    int main()
    {
        //freopen("aa.txt","r",stdin);
        int n,e,i,a,b,j;
        while(scanf("%d%d",&n,&e)!=EOF)
        {
            S.clear();
            memset(temp,0,sizeof(temp));
            memset(flag,0,sizeof(flag));
            for(i=0;i<e;i++)
            {
                scanf("%d%d",&a,&b);
                temp[a][b]=1;
                temp[b][a]=1;
            }
            for(i=0;i<n;i++)
            {
                for(j=0;j<n;j++)
                {
                    cout<<temp[i][j]<<' ';
                }
                cout<<endl;
            }
            for(i=0;i<n;i++)
            {
                if(!flag[i])
                {
                    flag[i]=1;
                    bfs(i,n);
                }
            }
            cout<<endl;
        }
        return 0;
    } 
    

      

  • 相关阅读:
    nowcoderD Xieldy And His Password
    Codeforces681D Gifts by the List
    nowcoder80D applese的生日
    Codeforces961E Tufurama
    Codeforces957 Mahmoud and Ehab and yet another xor task
    nowcoder82E 无向图中的最短距离
    nowcoder82B 区间的连续段
    Codeforces903E Swapping Characters
    Codeforces614C Peter and Snow Blower
    Codeforces614D Skills
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3436643.html
Copyright © 2011-2022 走看看