1. 程式人生 > >資料結構實驗之圖論一:基於鄰接矩陣的廣度優先搜尋遍歷

資料結構實驗之圖論一:基於鄰接矩陣的廣度優先搜尋遍歷

0 3 4 2 5 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 101
int book[max];
int df[max][max];
int num[max],queue[max];
int top,front,rear;

void bfs (int x)
{
    int i,j;
    book[x]=1;
    rear++;
    queue[rear]=x;
    while(front!=rear)
    {
        front++;
        i=queue[front];
        num[++top]=i;
        for(j=0;j<max;j++)
        {
            if(df[i][j]&&book[j]==0)
            {
                rear++;
                queue[rear]=j;
                book[j]=1;
            }
        }
    }
}
int main()
{
    int i,n,k,m,u,v,t;
    scanf("%d",&n);
    while(n--)
    {
        top=-1;
        front=rear=0;
        memset(book,0,sizeof(book));
        memset(df,0,sizeof(df));
        scanf("%d%d%d",&k,&m,&t);
        while(m--)
        {
            scanf("%d%d",&u,&v);
            df[u][v]=df[v][u]=1;
        }
        bfs(t);
        for(i=0;i<=top;i++)
        {
            printf("%d%c",num[i],(i==top?'\n':' '));
        }
    }
    return 0;
}