题目:图的广度优先遍历
问题描述
已知无向图的邻接矩阵,以该矩阵为基础,给出广度优先搜索遍历序列,并且给出该无向图的连通分量的个数。在遍历时,当有多个点可选时,优先选择编号小的顶点。(即从顶点1开始进行遍历)
输入格式
第一行是1个正整数,为顶点个数n(n<100),顶点编号依次为1,2,…,n。后面是邻接矩阵,n行n列。
输出格式
共2行。第一行输出为无向图的广度优先搜索遍历序列,输出为顶点编号,顶点编号之间用空格隔开;第二行为无向图的连通分量的个数。
样例输入
6
0 1 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0
样例输出
1 2 5 6 3 4
2
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct Queue
{
int num;
struct Queue* next;
}Queue, *LinkQueue;
typedef struct Pointer
{
LinkQueue front;
LinkQueue rear;
}Pointer, *ThePointer;
void EnQueue(int num, ThePointer pointer);
int DeQueue(ThePointer pointer);
int main()
{
int n;
int arcs[100][100];
int i, j;
int count = 0;
int visited[100] = { 0 };
ThePointer pointer = (ThePointer)malloc(sizeof(Pointer));
pointer->front = (LinkQueue)malloc(sizeof(Queue));
pointer->rear = pointer->front;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%d", &arcs[i][j]);
}
}
for (i = 1; i <= n; i++)
{
if (visited[i] == 0)
{
count++;
EnQueue(i, pointer);
visited[i] = 1;
printf("%d ", i);
while (pointer->front != pointer->rear)
{
int e = DeQueue(pointer);
for (j = 1; j <= n; j++)
{
if (arcs[e][j] == 1 && visited[j] == 0)
{
EnQueue(j, pointer);
visited[j] = 1;
printf("%d ", j);
}
}
}
}
}
printf("\n%d", count);
return 0;
}
void EnQueue(int num, ThePointer pointer)
{
LinkQueue q = (LinkQueue)malloc(sizeof(Queue));
q->num = num;
q->next = NULL;
pointer->rear->next = q;
pointer->rear = q;
}
int DeQueue(ThePointer pointer)
{
int e = pointer->front->next->num;
LinkQueue q = pointer->front->next;
if (pointer->front->next == pointer->rear)
{
pointer->rear = pointer->front;
}
pointer->front->next = pointer->front->next->next;
free(q);
return e;
}