List connected sets (traversal of graph)

Foreword

The traversal of the picture, hahaha was actually made so quickly, it can be, first code the code today, fill the hole tomorrow.

topic

Given an undirected graph with N vertices and E edges, use DFS and BFS to list all its connected sets. Suppose vertices are numbered from 0 to N−1. When performing a search, it is assumed that we always start from the vertex with the lowest number and visit adjacent points in the order of increasing number.

Input format

Entering the first line gives two integers N (0 <N≤10) and E, which are the number of vertices and edges of the graph, respectively. Then in line E, each line gives two endpoints of an edge. The numbers in each line are separated by 1 space.

Output format

According to "{ v​1 v2 ... vk }"the format, each line outputs a connected set. The DFS result is output first, followed by the BFS result.

Sample

Input sample

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 }

Ideas

achieve

Complete code

#include<iostream>
using namespace std;

const int MaxSize = 11;
int visit[MaxSize] = { 0, };
//邻接矩阵存储图:一个顶点结构存储顶点的相关信息,一个主体结构存储图的信息
//在本题中,因为不需要多余的顶点信息,所以把顶点的结构简化了


typedef struct {
	int edges[MaxSize][MaxSize];
	int n, e;
}MGraph;

//总是从最小的顶点出发,那就是从0出发进行遍历
void myInput(MGraph &g);
void myBFS(MGraph g);
void myDFS(MGraph g);
void myDFS_visit(MGraph g, int p);

int main() {
	MGraph G;
	int N, E;
	cin >> N >> E;
	G.n = N;
	G.e = E;
	for (int i = 0; i < N; i++)			//初始化
		for (int j = 0; j < N; j++) 
			G.edges[i][j] = -1;
	myInput(G);
	myDFS(G);
	for (int i = 0; i < MaxSize; i++)
		visit[i] = 0;
	myBFS(G);
	return 0;
}

void myInput(MGraph &g) {
	for (int i = 0; i < g.e; i++) {
		int v1, v2;
		cin >> v1 >> v2;
		g.edges[v1][v2] = g.edges[v2][v1] = 1;
	}
}

void myBFS(MGraph g) {			//用矩阵可以更好的实现从小到大访问
	int queue[MaxSize];
	int front, rear;
	front = rear = -1;
	for (int i = 0; i < g.n; i++) {
		if (visit[i] == 0) {
			cout << "{ " << i <<" ";
			queue[++rear] = i;			//最小元素入队
			visit[i] = 1;						//0已经访问过了
			while (front != rear) {
				int p = queue[++front];
				for (int j = i; j < g.n; j++)
					if (g.edges[p][j] == 1 && visit[j] == 0) { 		//联通的且未访问过的,入栈
						queue[++rear] = j;
						cout << j << " ";
						visit[j] = 1;
					}
			}
			cout << "}\n";
		}
	}
	return;
}

void myDFS(MGraph g) {
	for (int i = 0; i < g.n; i++) 
		if (visit[i] == 0) {
			cout << "{ ";
			myDFS_visit(g, i);
			cout << "}\n";
		}
	return;
}

void myDFS_visit(MGraph g, int p) {
	cout << p << " ";
	visit[p] = 1;
	for (int i = 0; i < g.n; i++) 
		if (g.edges[p][i] == 1 && visit[i] == 0) 
			myDFS_visit(g, i);
	return;
}

Guess you like

Origin www.cnblogs.com/Za-Ya-Hoo/p/12748946.html