06-图1 列出连通集 (25分)

https://blog.csdn.net/rnzhiw/article/details/81408268 一样贴一个好的网站关于理解广度搜索的,dfs 和bfs 一个靠堆栈,一个靠队列,第一个多去理解下靠堆栈实现的递归,进而理解回朔,第二个这个网站很详细了
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int m[10][10];
int flag[10];
void dfs(int i, int n)         //i时开始寻找的结点下标
{
	int j;
	flag[i] = 1;
	cout << " " << i;
	for (j = 0; j < n; j++) {
		if (!flag[j] && m[i][j])
			dfs(j, n);
	}
}
void bfs(int i, int n)
{
	flag[i] = 1;
	queue<int>q;
	q.push(i);
	while (!q.empty()) {
		int top = q.front();
		cout << " " << top;
		q.pop();
		int j;
		for (j = 0; j < n; j++) {
			if (!flag[j] && m[top][j] == 1) {
				q.push(j);
				flag[j] = 1;
			}
		}
	}
}
int main()
{
	int n, e, i, x, y;
	cin >> n >> e;
	memset(flag, 0, sizeof(flag));
	for (i = 0; i < e; i++) {
		cin >> x >> y;
		m[x][y] = m[y][x] = 1;
	}
	for (i = 0; i < n; i++) {
		if (!flag[i]) {
			cout << "{";
			dfs(i, n);
			cout << " }" << endl;
		}
	}
	memset(flag, 0, sizeof(flag));
	for (i = 0; i < n; i++) {
		if (!flag[i]) {
			cout << "{";
			bfs(i, n);
			cout << " }" << endl;
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13109998.html