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

来源:互联网 发布:c语言 void main 编辑:程序博客网 时间:2024/06/01 21:50

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


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

16 7 00 30 41 41 52 32 43 5

Example Output

0 3 4 2 5 1

Hint

以邻接矩阵作为存储结构。


解题思路
广度优先搜索遍历过程用队列来实现,首先将遍历的起始顶点作为队头,访问,依次将未被访问的邻接点入队。。。当front=rear时,队列已满,访问结束。


代码

#include <stdio.h>#include <stdlib.h>int map[100][100],visited[100],q[100],k;void bfs(int top){    int front=0,rear=0;    printf("%d",top);    q[rear++]=top;    while(front!=rear)//队列未满    {        int f,i;        f=q[front++];        for(i=0;i<k;i++)        {            if(map[f][i]==1&&visited[i]==0)//判断邻接点是否被访问过            {                visited[i]=1;                printf(" %d",i);                q[rear++]=i;            }        }    }}int main(){    int n;    scanf("%d",&n);    while(n--)    {        int m,t,u,v;        memset(map,0,sizeof(map));        memset(visited,0,sizeof(visited));        scanf("%d%d%d",&k,&m,&t);        while(m--)//建立图的邻接矩阵        {            scanf("%d%d",&u,&v);            map[u][v]=1;            map[v][u]=1;        }        visited[t]=1;        bfs(t);    }    return 0;}

代码(队列)

#include <iostream>#include <queue>#include <cstring>using namespace std;int k,m,n;int u,v;bool vis[105];int mmap[105][105];void bfs(int n){    queue<int>q;//建立队列    q.push(n);//将出发顶点压入队列(入队)    while(!q.empty())    {        int now=q.front();        q.pop();//将顶点弹出(出队)        for(int i=0;i<k;i++)//寻找当前定点(即now)的邻接点i        {            if(!vis[i]&&mmap[now][i]==1)            //如果邻接点没有被访问过并且与当前接点有边            {                vis[i]=1;                q.push(i);//将邻接点压入队列(入队)                cout<<" "<<i;            }        }    }}int main(){    int t;    cin>>t;    while(t--)    {        memset(vis,false,sizeof(vis));        memset(mmap,0,sizeof(mmap));        cin>>k>>m>>n;//k为顶点个数,m为边数,n为出发顶点        while(m--)        {            cin>>u>>v;            mmap[u][v]=mmap[v][u]=1;//建立无向图        }        cout<<n;//先输出出发顶点        vis[n]=1;//将出发顶点标记为访问        bfs(n);//进行广度优先搜索        cout<<endl;    }    return 0;}
阅读全文
1 0
原创粉丝点击