在图中找到最短的周期(无向,无权)

时间:2019-12-09 17:08:37

标签: python python-3.x algorithm graph graph-algorithm

我一直在尝试编写一个在图形中找到最短周期的python程序,但是我陷入了困境。这是我的代码:

def shortestCycle(vertices):

    distances = []

    for i in range(len(vertices.keys())):
        dist = 0
        visited = []
        vertex = list(vertices.keys())[i]
        searchQueue = deque()

        searchQueue += vertices[vertex]

        while searchQueue:
            currentVertex = searchQueue.popleft()   
            if currentVertex not in visited:

                if currentVertex == vertex:
                    break
                else:
                    visited.append(currentVertex)
                    searchQueue += vertices[currentVertex]
            dist += 1
        distances.append(udaljenost)


    return min(distances)

对于某些额外的解释,vertices是一个以顶点为键,而其邻居为值的字典,例如:{1 : [2, 4, 5, 8], 2 : [1, 3], ...。这段代码给出了错误的结果,我对导致该结果的原因不完全了解,但不确定如何解决。有什么想法或建议吗?

编辑:

示例输入:{'1': ['2', '4', '5', '8'], '2': ['1', '3'], '3': ['2', '4'], '4': ['1', '3'], '5': ['1', '6'], '6': ['5', '7'], '7': ['6', '8'], '8': ['1', '7']}

示例输出:4

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题:

def shortestCycle(vertices):


    minCycle = sys.maxsize
    n = len(vertices.keys())

    for i in range(n):

        distances = [sys.maxsize for i in range(n)]
        parent = [-1 for i in range(n)]

        distances[i] = 0


        q = deque()
        q.append(i + 1)


        while q:

            currentVertex = str(q.popleft())


            for v in vertices[currentVertex]:

                j = currentVertex
                if distances[v - 1] == sys.maxsize:
                    distances[v - 1] = 1 + distances[j - 1]

                    parent[v - 1] = j

                    q.append(v)

                elif parent[j - 1] != v and parent[v - 1] != j - 1:

                    minCycle = min(minCycle, distances[j - 1] + distances[v - 1] + 1)

        if minCycle == sys.maxsize:
            return -1
        else:
            return minCycle