/*邻接矩阵形式给出无向连通图,确定其是否为树
连通图中,存在一条一节点到任意其他节点的路径,此节点未必是直接连接节点的一条边
连通图(nXn个顶点)其邻接矩阵是n*n的二维矩阵,如果从ith到jth有一条边,则该位置为1;
否则为0;
函数isTree输入包含邻接矩阵grid,和顶点数n;
图为树则返回1,否则返回0*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int grid[100][100];
int find(int x, vector<int> &f)
{
return x == f[x] ? x : f[x] = find(f[x], f);
}
void merge(int x, int y, vector<int> &f)
{
int fa, fb;
fa = find(x, f);
fb = find(y, f);
if (fa == fb) return;
f[fb] = fa;
}
int isTree(int n)
//int isTree(int **grid,int n)
{
if (n == 0) return 1;
//int ff[100];
vector<int> f;
int i, j;
int fa, fb;
int count = 0;
int sum = 0;
for (i = 0; i < n; i++) {
f.push_back(i);
}
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
if (grid[i][j] == 0) continue;
sum++;
fa = find(i, f);
fb = find(j, f);
if (fa == fb) return 0;
merge(i, j, f);
}
}
for (i = 0; i < n; i++) {
if (i == find(i, f)) {
count++;
}
}
if (sum != n - 1) return 0;
if (count == 1) {
return 1;
}
else {
return 0;
}
}
int main()
{
//freopen_s("in.txt", "r", stdin);
int n, re;
int i, j;
cin >> n;
//while (scanf("%d", &n) != EOF)
{
printf("%d\n", n);
for (i = 0; i<n; i++) {
for (j = 0; j<n; j++) {
//scanf("%d", &grid[i][j]);
cin >> grid[i][j];
}
}
re = isTree(n);
printf("%d\n", re);
}
cout << "Hello world!" << endl;
return 0;
}
找树!
最新推荐文章于 2022-12-07 09:47:00 发布