九度 题目1012:畅通工程 (BFS计算连通分支的个数)

用宽搜(bfs)计算图的连通分支的个数bfs_cnt。需要构建的道路的条数为bfs_cnt - 1


代码:

#include <iostream>
#include <queue>

using namespace std;

int n, m, bfs_cnt;
bool connect[1010][1010];
bool vi[1010];
queue<int> q;

void init()
{
	for (int i = 1; i <= n; ++ i)
	{
		vi[i] = false;
		for (int j = 1; j <= n; ++ j)
		{
			connect[i][j] = false;
		}
	}
	while (q.empty() == false) { q.pop();}
	bfs_cnt = 0;

	cin >> m;
	for (int i = 0; i < m; ++ i)
	{
		int a, b;
		cin >> a >> b;
		connect[a][b] = connect[b][a] = true;
	}
}

void bfs(int index)
{
	++ bfs_cnt;
	q.push(index);
	while (q.empty() == false)
	{
		int v = q.front();
		vi[v] = true;
		for (int j = 1; j <= n; ++ j)
		{
			if (vi[j]==false && connect[v][j])
			{
				q.push(j);
			}
		}
		q.pop();
	}
}

int main()
{
	while (cin >> n, n)
	{
		init();
		for (int i = 1; i <= n; ++ i)
		{
			if (vi[i] == false)
			{
				bfs(i);
			}
		}
		cout << bfs_cnt - 1 << endl;
	}
	return 0;
}


你可能感兴趣的:(C++,bfs,九度,Jobdu)