图论中不连通图的块数

#include "iostream"
#include "memory.h"
using namespace std;

int grap[100][100];
int n, m;
int ans = 0; //保存不连通图的块数 
bool flag = false;
void dfs(int x){
	for (int i = 0; i < n; i++){
		if (grap[x][i] == 1){ //找到新的连通节点
			grap[x][i] = 0;
			flag = true;
			dfs(i);	
		}
	}
}
int main(){
	
	while (cin >> n >> m){
		ans = 0;
		memset(grap, 0, sizeof(grap));
		if (n == 0 && m == 0)
			break;
		// 若两个点a, b有连线,则grap[a][b]和grap[b][a]为1
		for (int i = 0; i < m; i++){
			int a, b;
			cin >> a >> b;
			grap[a][b] =1;
			grap[b][a] = 1;
		}
		for (int i = 0; i < n; i++)
			grap[i][i] = 1;
		for (int i = 0; i < n; i++){
			flag = false;
			dfs(i);
			if (flag)
				ans++;
		}
		cout << ans-1<< endl;
	}
}

你可能感兴趣的:(图论中不连通图的块数)