Fork me on GitHub

06-图1 列出连通集

题目

  • 给定一个有NN个顶点和EE条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N-1N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:

  • 输入第1行给出2个整数NN(0<N\le 100<N≤10)和EE,分别是图的顶点数和边数。随后EE行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

输出格式:

  • 按照"{ v1 v​2 ... vk }"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。

输入样例:

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

输出样例:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

AC代码

/*!
 * \file 06-图1 列出连通集.cpp
 *
 * \author ranjiewen
 * \date 2017/04/12 21:42
 *
 * 
 */

/*图的邻接矩阵表示简化法*/

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

#define MaxSive 10

int  graph[MaxSive][MaxSive];
int Nv, Ne;
int check[MaxSive];

void buildGraph()
{
	int V1, V2;
	scanf("%d %d",&Nv, &Ne);
	//CreateGraph
	for (int i = 0; i < Nv;i++)
	{
		check[i] = 0;
		for (int j = 0; j < Ne;j++)
		{
			graph[i][j] = 0;
		}
	}

	for (int i = 0; i < Ne; i++)
	{
		scanf("%d %d",&V1,&V2); //可以再增加权重
		//InsertEdge
		graph[V1][V2] = 1;
		graph[V2][V1] = 1;
	}
}

int checkVisited()
{
	int i;
	for (i = 0; i < Nv;i++)
	{
		if (!check[i])
		{
			break;
		}
	}
	if (i==Nv) 
	{
		return -1;
	}
	return i;
}

void BFS()
{
	queue<int> Q;
	int i, j;
	i = checkVisited();
	if (i==-1)
	{
		return;
	}
	Q.push(i);
	check[i] = true;
	printf("{ %d ", i); //顶点从0开始编号 //控制流的输出方式
	while (!Q.empty())
	{
		int temp = Q.front();
		Q.pop();
		for (j = 0; j < Nv;j++)
		{
			if (graph[temp][j]==1&&!check[j])
			{
				check[j] = 1;
				printf("%d ", j);
				Q.push(j);
			}
		}
	}
	printf("}\n");
	return BFS();  //采用尾递归
}

void DFS(int V)
{
	check[V] = 1;
	printf("%d ",V);
	for (int i = 0; i < Nv; i++)
	{
		if (graph[V][i]==1&&!check[i])
		{
			DFS(i);
		}
	}
}

void DFSList()
{
	for (int i = 0; i < Nv;i++)
	{
		if (check[i]==0)
		{
			printf("{ ");
			DFS(i);
			printf("}\n");
		}
	}
}

int main()
{
	buildGraph();

	DFSList();
	
	//memset(check, 0, sizeof(int)*MaxSive);
	for (int i = 0; i < Nv; i++)
	{
		check[i] = 0;
	}

	BFS();

	return 0;
}

来源

posted @ 2017-04-12 22:54  ranjiewen  阅读(574)  评论(0编辑  收藏  举报