简体   繁体   中英

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. 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], ... . 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']}

example output: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM