zoukankan      html  css  js  c++  java
  • 数据结构实验之图论二:基于邻接表的广度优先搜索遍历

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

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

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

    Input

    输入第一行为整数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顶点的无向边。

    Output

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

    Example Input

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

    Example Output

    0 3 4 2 5 1

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <queue>


    using namespace std;
    struct node
    {
    int v;
    node *next;
    }*a[123];
    int n,m;
    int vis[123];
    void add(int x,int y)
    {
    node *p = a[x];
    while(p->next &&p->next->v<y)
    {
    p=p->next;
    }
    node *q = new node;
    q->v = y,q->next=p->next,p->next = q;
    }
    void BFS(int k)
    {
    queue<int>q;
    q.push(k);
    vis[k] = 1;
    int cnt=0;
    while(!q.empty())
    {
    int u = q.front();
    q.pop();
    printf(cnt==0?"%d":" %d",u);
    cnt++;
    node *p = a[u]->next;
    while(p)
    {
    if(!vis[p->v])
    {
    vis[p->v] = 1;
    q.push(p->v);
    }
    p=p->next;
    }
    }
    }
    int main()
    {
    int T,i,t;
    scanf("%d",&T);
    while(T--)
    {
    scanf("%d%d%d",&n,&m,&t);
    memset(vis,0,sizeof(vis));
    for(i=0;i<m;i++)
    {
    a[i] = new node;
    a[i]->next = NULL;
    }
    for(i=0;i<m;i++)
    {
    int v,u;
    scanf("%d%d",&v,&u);
    add(v,u);
    add(u,v);
    }
    BFS(t);
    printf("\n");
    }
    return 0;
    }

  • 相关阅读:
    LINUX 新手 入门 教程
    mysql 新手入门 官方文档+官方中文文档附地址
    Git常用命令
    修改dotnet运行.netcore web程序默认端口
    centos7.6下部署.netcore3.1web程序
    supervisor安装及使用(转载)
    linux(CentOS7.6)下安装mysql8.0并使用navicat远程访问
    uni-app为组件uni-icons增加自定义图标(超简单)
    常用正则表达式收录(持续更新)
    CentOS7.6安装SQL SERVER 2017
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/6444572.html
Copyright © 2011-2022 走看看