#include<bits/stdc++.h>
using namespace std;
typedef struct Arcnode {
int adjvex;
struct Arcnode* nextarc;
}Arcnode;
typedef struct Vnode {
int data;
Arcnode* firstarc;
}Vnode,AdjList[1024];
typedef struct ALGraph {
int vexnum, arcnum;
AdjList vertices;
}ALGraph;
int visited[1024] = { 0 };
int num = 0;
void DFS(ALGraph G, int u) {
Arcnode* s[1024] = { 0 };
int top = -1;
num++;
s[++top] = G.vertices[u].firstarc;
visited[u] = 1;
while (top != -1) {
Arcnode* p = s[top];
while (p != NULL) {
if (visited[p->adjvex] == 0) {
s[++top] = G.vertices[p->adjvex].firstarc;
visited[p->adjvex] = 1;
break;
}
p = p->nextarc;
}
if (p == NULL) top--;
}
}
void DFSTrave(ALGraph G, int n) {
int i;
for (i = 1; i <= n; i++) {
if (visited[i] == 0)
DFS(G, i);
}
if (num == 1)
cout << num;
else cout << 0;
}
void create(ALGraph& G) {
cin >> G.vexnum >> G.arcnum;
int i;
for (i = 1; i <= G.vexnum; i++) {
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
for (i = 1; i <= G.arcnum; i++) {
Arcnode* p = new Arcnode;
Arcnode* q = new Arcnode;
cin >> p->adjvex >> q->adjvex;
q->nextarc = G.vertices[p->adjvex].firstarc;
G.vertices[p->adjvex].firstarc = q;
p->nextarc = G.vertices[q->adjvex].firstarc;
G.vertices[q->adjvex].firstarc = p;
}
}
void main() {
ALGraph G;
create(G);
if (G.arcnum + 1 != G.vexnum) {
cout << 0;
return;
}
DFSTrave(G, G.vexnum);
}
判断该无向图G是否是一棵树
于 2023-02-06 00:21:43 首次发布