List Components

粘题目:

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS and BFS. Assume that all the vertices are numbered from 0 to N-1. While searching, assume that we always start from the vertex with the smallest index, and visit its adjacent vertices in ascending order of their indices.

Input Specification:

Each input file contains one test case. For each case, the first line gives two integers N (0<N<=10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in each line a connected component in the format "{ v1 v2 ... vk }". First print the result obtained by DFS, then by BFS.

Sample Input:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
Sample Output:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

说下题的输入和输出

输入:

第一行顶点的个数和边的个数

· 后面是每条边所对应的2个顶点

输出:

就是输出DFS和BFS序列,注意点格式就好


今天的这道题就是求图的DFS和BFS遍历序列,存储图时我使用了图的邻接矩阵存储,当然也可以使用邻接表,请自己尝试,本题比较简单,直接上代码:

#include<iostream>
#include<queue>
#define MaxSize 100
using namespace std;
typedef int ElemType;

typedef struct
{
	ElemType vex[MaxSize];
	bool flag[MaxSize][MaxSize];
	int vexnum;
	int edg;
}Graph;
bool visited[MaxSize];
void DFS(Graph G, int v)
{
	cout << v<<" ";
	visited[v] = true;
	for (int i = 0; i < G.vexnum; i++)
	{
		if (G.flag[v][i] == true && (!visited[i]))
			DFS(G, i);
	}
}

void DFSTraverse(Graph G)
{
	for (int v = 0; v < G.vexnum; v++)
		visited[v] = false;
	for (int v = 0; v < G.vexnum; v++)
	{
		if (!visited[v])
		{
			cout << "{ ";
			DFS(G,v);
			cout << "}" << endl;
		}
	}
}

void BFS(Graph G,int v)
{
	cout << v << " ";
	visited[v] = true;
	queue<ElemType> q;
	q.push(v);
	while (!q.empty())
	{
		v = q.front();
		q.pop();
		for (int w = 0; w < G.vexnum; w++)
		{
			if (!visited[w] && G.flag[v][w])
			{
				cout << w << " ";
				visited[w] = true;
				q.push(w);
			}
		}
	}
}

void BFSTraverse(Graph G)
{
	for (int v = 0; v < G.vexnum; v++)
		visited[v] = false;
	for (int v = 0; v < G.vexnum; v++)
	{
		if (!visited[v])
		{
			cout << "{ ";
			BFS(G, v);
			cout << "}" << endl;
		}
	}
}
int main()
{
	int N, E;
	cin >> N >> E;
	Graph G;
	G.vexnum = N;
	G.edg = E;
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
			G.flag[i][j] = false;                       //初始化
	//构造一个二维数组存储是否有边
	for (int i = 0; i < E; i++)
	{
		ElemType a, b;
		cin >> a >> b;
		G.flag[a][b] = true;
		G.flag[b][a] = true;
	}   
	for (int i = 0; i < N; i++)
	{
		G.vex[i] = i;
	}
	DFSTraverse(G);
	BFSTraverse(G);
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值