/**
*
* 判断图是否有根
*
* ①算法思想
* 如果从一个顶点开始可以到达其他所有的顶点,那么这个顶点就是这个图的根,
* 可以使用DFS,用count计数,最后将遍历的顶点个数count和图的顶点个数vexnum进行比较来判断这个顶点是否为根;
* 当然要for循环一一判断所有的顶点中是否有能成为根的顶点。
*
* ②算法设计
*
*/
#include <stdio.h>
#include <iostream>
#include <cstdio>
#include <malloc.h>
#include <cstdlib>
#define MaxSize 20
#define INF 999999
//判断图是否有根
struct ArcNode{
int adjvex;
struct ArcNode *next;
int weight;
};
struct VNode{
char value;
struct ArcNode *first;
};
struct AdGraph{
VNode vertices[MaxSize];
int vexnum,arcnum;
};
void DFS(AdGraph G,int v,int &count,int *visited){
visited[v] = 1;
count++;
ArcNode *p = G.vertices[v].first;
while(p){
if(visited[p -> adjvex] == 0){
DFS(G,p -> adjvex,count,visited);
}
p = p -> next;
}
}
bool IsRoot(AdGraph G){
int count = 0,visited[MaxSize];
for (int i = 0; i < G.vexnum; ++i) {
visited[i] = 0;
}
for (int i = 0; i < G.vexnum; ++i) {//for循环一一判断所有的顶点中是否有能成为根的顶点
count = 0;
DFS(G,i,count,visited);
if(count == G.vexnum)
return true;
}
return false;
}
判断图是否有根
于 2022-09-19 16:25:04 首次发布