无向图的所有环
无向图在实际应用中是极其常见的一种抽象形式,几乎所有能抽象为两两关系的数据都能转化为无向图,每个环都包含了许多有价值的信息,例如交通网络中的无向图的环表示一个连通的路线,因此,求它的所有环具有十分重要的现实意义。
在此,我们使用最经典的DFS寻找无向图的所有环。
实现过程
- 选取任意一个顶点作为起点,然后以该顶点为起点开始进行深度优先搜索。
- 记录当前搜索路径上已经访问过的所有顶点,并将这些顶点保存在列表中。
- 在搜索时,对于每个邻居节点,若它已经被访问过,则检查它是否在当前路径上(即是否是之前经过的顶点之一),如果是,则表示找到了一条环,输出环中包含的所有顶点。
- 继续深度优先搜索,直到所有路径都被遍历完。
python代码
# G:无向图的邻接表、length:长度为length的环、path:环的路径、circles:存储每个环的节点
def find_cir_starts_with(G, length, path, circles):
l, last = len(path), path[-1]
if l == length - 1: # choose the final node in the circle
for i in G[last]:
if (i > path[1]) and (i not in path) and (path[0] in G[i]):
print(path + [i])
circles.append(path + [i]) # 找到环,存入circles
else:
for i in G[last]: # choose internal nodes in the circle
if (i > path[0]) and (i not in path):
find_cir_starts_with(G, length, path + [i], circles)
def find_cir_of_length(G, n, length, circles):
for i in range(1, n - length + 2): # 找i节点开头的所有环(i=1,2,...)
find_cir_starts_with(G, length, [i], circles)
# 将所有环存入全局变量circles中
def find_all_cirs(G, n, circles):
for i in range(3, n + 1): # 找长度为i的所有环(i=3,4,...)
find_cir_of_length(G, n, i, circles)
测试代码如下:
circles = []
G = {
1: [2, 5],
2: [1, 3],
3: [2, 4],
4: [3, 5],
5: [1, 4],
6: [7, 10],
7: [6, 8],
8: [7, 9],
9: [8, 10],
10: [6, 9],
11: [12, 15],
12: [11, 13],
13: [12, 14],
14: [13, 15],
15: [11, 14]
}
find_all_cirs(G, len(G.keys()), circles)