xdoj 图的广度优先遍历

题目:图的广度优先遍历

问题描述

已知无向图的邻接矩阵,以该矩阵为基础,给出广度优先搜索遍历序列,并且给出该无向图的连通分量的个数。在遍历时,当有多个点可选时,优先选择编号小的顶点。(即从顶点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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值