简体   繁体   中英

Using BFS to find smallest cycle that includes origin in O(V+E)

Hello I have been trying to figure out how to solve this problem.

You are given an undirected graph G, you start at source s. And the goal is the to visit as few vertices while never covering the same edge twice and come back in a loop.

Note it is possible that no such loop exists. So how do we find the smallest cycle that includes the origin?

For example

s-----o
| \   |
|  \  |
|   \ |
o----\o

The shortest cycle would be either the upper triangle or the lower triangle

I think there's a way to solve this with BFS. But I am not sure how do you find the path of the cycle exactly?

Try this, when you start BFS mark all the nodes oh depth 1 (the origin children) with a different id (eg. 0, 1, 2, ...etc) then all the nodes that follows will have his parent id. As the algorithm runs you have to check if two nodes with different ids are connected, the first time that occurs will show you the smallest cycle that contains the origin (which is the edge that connected those two nodes of different ids (lets name they v1 and v2 ) plus all the path from v1 to the origin plus all the path from v2 to the origin)

Eg. Suppose you are running the algorithm in this graph:

 S ----- v1 ----- v2
 |       |        |
 v3 ---- v4 ----- v5
  • First you start at the origin S
  • Then all the s children ( v1 and v3 ) are added to the queue (in this moment you assign their ids). In this case lets assume v1.id = 0 and v2.id = 1 .
  • Now you dequeue S and take v1 as current
  • v1 has tow children so you add them to the queue (and assign them the same id as they parent: v2.id = current.id and v4.id = current.id )
  • Now you dequeue v1 and take the newx node in the queue which is v3 as current
  • v3 has two children, one of them is the origin which is an special case, and the other is v4 . But v4 has been already visited and it has a different id than v3 (Here the algorithm stop because you found the cycle which is: S - v1 - v4 - v3 - S

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