1.基本思想
判断图是不是树,一个方法是判断这个图中有没有回路。
a.深度递归找到一条路径,记结点加入路径的顺序为1,2,…,i-1,i
b.对每个新加入路径的点i,按c检查周围一圈邻接点
c.除了i-1(走到i,是从i-1走过来的),其他点中,如果有“访问过”的点,即说明有回路。
2.代码
bool isTree(GraphList G, int up, int now) {
G.Mark[now] = VISITED;
cout << now;
//检查一圈
for (Edge e = G.FirstEdge(now); G.isEdge(e); e = G.NextEdge(e)) {
if (G.Mark[e.to] == VISITED && e.to != up) {
cout << "有回路"<<e.to<<" "<<now << endl;
return false;
}
}
for (Edge e = G.FirstEdge(now); G.isEdge(e); e = G.NextEdge(e)) {
if (G.Mark[e.to]==UNVISITED)
if (!isTree(G, now, e.to)) {
return false;
}
}
return true;
}
1.如果满足回路条件(见1.c)则返回false,通知上一层递归也返回false。
2.最后一行return true的意思是,以当前now为源点的“子图”构成树
3.往下递归的时候,当前层都要把当前层踩住的结点(i-1)告知下一层,以让下一层进行判断。
测试用例
if (isTree(TreeorGraph, -1, 0))
cout << "是树";
else
cout << "不是树";
1.无向图1的构造,这里不同于有向图,每个点的邻接边既算入度也算出度
GraphList TreeorGraph(7);
int from3[] = { 0,0,1,1,2,3,3,4,5 };
int to3[] = { 1,4,3,2,6,5,6,5,6 };
int weight3[] = { 20,1,4,6,2,12,8,15,10 };
for (int i = 0; i < 9; i++) {
TreeorGraph.setEdge(from3[i], to3[i], weight3[i]);
TreeorGraph.setEdge(to3[i], from3[i], weight3[i]);
}
输出:
2.无向图2。我们在无向图1的基础上划掉三条边
GraphList TreeorGraph(7);
int from3[] = { 0,1,2,3,4,5 };
int to3[] = { 4,2,6,5,5,6 };
int weight3[] = { 20,1,4,6,2,12 };
for (int i = 0; i < 6; i++) {
TreeorGraph.setEdge(from3[i], to3[i], weight3[i]);
TreeorGraph.setEdge(to3[i], from3[i], weight3[i]);
}
输出: