-3

Trying to understand graphs and having a really hard time with this. I know how to find the shortest path, but not sure how you can find the shortest cycle and still make it in O(n+m) time?

ka123444
  • 15
  • 1
  • 4

1 Answers1

0

the shortest cycle that contains e

BFS is perfect for that. A cycle will be the goal. Time complexity is the same.

You want something like this(Edited from Wikipedia):

Cycle-With-Breadth-First-Search(Graph g, Edge e):

    remove e from E
    root is b where e = (a,b)
    create empty set S
    create empty queue Q      

    root.parent = a
    Q.enqueueEdges(root)                      

    while Q is not empty:

        if current = a
            return current

        current = Q.dequeue()
        for each node n that is adjacent to current:
            if n is not in S:
                add n to S
                n.parent = current
                Q.enqueue(n)

For more info about cycles and BFS read this link https://stackoverflow.com/a/4464388/6782134

Community
  • 1
  • 1
Dolev
  • 654
  • 11
  • 20