简体   繁体   English

在图中找到最短的周期(无向、未加权)

[英]Find the shortest cycle in a graph (Undirected, Unweighted)

I've been trying to write a python program that finds the shortest cycle in a graph, but I'm stuck.我一直在尝试编写一个 python 程序,它可以在图中找到最短的循环,但我被卡住了。 This is my code:这是我的代码:

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)

For some extra explanation, vertices is a dictionary with vertices as keys, and their neighbours as values, for example: {1 : [2, 4, 5, 8], 2 : [1, 3], ... .对于一些额外的解释, vertices是一个字典,以顶点为键,它们的邻居为值,例如: {1 : [2, 4, 5, 8], 2 : [1, 3], ... This code gives the wrong result, and I'm partialy aware of what is causing that, but I'm not sure how to fix it.这段代码给出了错误的结果,我部分知道是什么原因造成的,但我不确定如何解决它。 Any ideas or advices ?任何想法或建议?

Edit:编辑:

example input: {'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']}示例输入: {'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']}

example output: 4示例输出: 4

I managed to solve it:我设法解决了它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 非加权图如何做最短路径算法? - How to do shortest path algorithm for unweighted graph? 从电子表格创建无向无权图的邻接矩阵 - Creating adjacency matrix for undirected unweighted graph from spreadsheet 从包含邻域关系的字典创建无向未加权图 - Creating undirected unweighted graph from dictionary containing neighborhood relationship 使用DFS检测无向图中的循环 - Detecting a cycle in an undirected graph using DFS 在无向图中找到长度为 4 的环 - find cycles of length 4 in undirected graph 在图中找到最短的三角形 - Find shortest triangle in a graph 无源和目标顶点的无向加权图的最短路径 - Shortest path for undirected weighted graph without source and target vertices 在十亿个节点的无向​​图中无循环地从正好k个边的源节点中找到目标节点的算法/方法 - Algorithm/Approach to find destination node from source node of exactly k edges in undirected graph of billion nodes without cycle 使用邻接矩阵(Python或伪代码)在拓扑排序的未加权有向无环图中的最短和最长路径 - Shortest and longest path in a topologically sorted unweighted directed acyclic graph using an adjacency matrix (Python, or pseudo-code) 在有向图和无向图中查找所有循环 - Find all cycles in directed and undirected graph
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM