算法在图中得到循环?

时间:2013-03-30 20:40:04

标签: python graph-theory graph-algorithm graph-traversal

如果你有一个表示为邻接列表的图形,你怎么能在python中检测到任何odd length-ed周期?

假设您有一个图表作为输入:

A = {
    1: [2, 4],
    2: [1, 5],
    3: [4, 5],
    4: [1, 3, 5],
    5: [2, 3, 4],
    6: []
}

V = {
    1: <node>,
    2: <node>,
    3: <node>,
    4: <node>,
    5: <node>,
    6: <node>
}

A是一个字典,其中键是一个数字,值是一个数字列表,因此在所有值的键之间存在一条边。 V是一个将数字映射到节点实例的字典。

如何检测是否存在奇怪的长度循环?

从上面的输入中,实际上有一个使用节点3, 4, 5

基本上我如何才能将输出变为3 4 5

由于

1 个答案:

答案 0 :(得分:1)

在图表中查找循环的常用方法是使用depth-first search算法。在您的情况下,我会用数字1和2标记每个顶点,以便所有相邻顶点具有不同的数字。如果你发现,有两个顶点具有相同的标记,这意味着你找到了一个奇数长度的循环。 这是我的简要实现(我没有使用V dictionaty,假设A不按原样描述图表:

import sys

A = {
    1: [2, 4],
    2: [1, 5],
    3: [4, 5],
    4: [1, 3, 5],
    5: [2, 3, 4],
    6: []
}

num_vertices = len(A)
sys.setrecursionlimit(num_vertices + 2)

mark = [None] * (num_vertices + 1)
cur_path = []

def DFS(vertex, cur_mark = 1):
    mark[vertex] = cur_mark
    global cur_path
    cur_path.append(vertex)
    for neighbour in A[vertex]:
        if not mark[neighbour]:
            DFS(neighbour, 3 - cur_mark)
        elif mark[neighbour] == cur_mark:
            print 'Found a loop of odd length: ', cur_path[cur_path.index(neighbour):]
            sys.exit(0)

    cur_path = cur_path[:-1]

# Visit all connected components
for vertex in xrange(1, num_vertices + 1):
    if not mark[vertex]:
        DFS(vertex)

print 'Cycle of odd length not found'