D - Experimental data structure of a Graph Theory: the adjacency matrix based on the breadth-first search traversal

Description

Given an undirected connected graph, vertices numbered from 0 to n-1, with a breadth-first search (BFS) traversal, traverse output sequence starting from a vertex. (With the same layer adjacent to a node point, a small number of nodes first traversal)
the Input

The first line input integer n (0 <n <100) , indicates the number of data sets.
For each test, the first three rows are integers k, m, t (0 < k <100,0 <m <(k-1) * k / 2,0 <t <k), expressed edges m , k vertices, t is the starting vertex traversal.
The following m lines, each line separated by a space of two integers u, v, represents a connector u, v vertices undirected edges.
Output

There are n output lines, an output corresponding to n groups, each separated by spaces behavior of integers k, corresponding to a set of data representing the results of the BFS traversal.
Sample

Input

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

0 3 4 2 5 1
Hint

In adjacency matrix as a storage structure.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#include<queue>
using namespace std;
int Map[110][110],vis[110];
int n,m;
void bfs(int t)
{
    queue<int>q;
    vis[t] = 1;
    q.push(t);
    int flag = 0;
    while(!q.empty())
    {
        int k = q.front();
        q.pop();
        if(flag == 0)
        {
            printf("%d",k);
            flag = 1;
        }
        else
            printf(" %d",k);
        for(int i=0;i<m;i++)
        {
            if(!vis[i]&&Map[k][i])
            {
                vis[i] = 1;
                q.push(i);
            }
        }
    }
}
int main()
{
    int t,p;
    int u,v;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d %d",&n,&m,&p);
        memset(vis,0,sizeof(vis));
        memset(Map,0,sizeof(Map));
        for(int i=0;i<m;i++)
        {
            scanf("%d %d",&u,&v);
            Map[u][v] = 1;
            Map[v][u] = 1;
        }
        bfs(p);
        printf("\n");
    }
    return 0;
}

Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104882719