Why DFS won't work
You cannot use DFS to find a shortest circle. We can easily create a counter example, where DFS leads finds only the longest circle. Lets have a look at the following graph:
As you can see we have nine nodes. If we start at the leftmost node A
, the following DFS level could be possible:
We have two back edges while iterating:
(B , A)
, therefore we found a circle with length 8
(D , A)
, therefore we found a circle with length 8
However, the shortest circle has length 5. It's shown in blue in the next picture, whereas one of the previously found circles is shown in red:
You didn't see the blue circle because your DFS path doesn't contain it.
Dagupa et al also mention this behaviour in their book:
But it also means that DFS can end up taking a long and convoluted route to a vertex that is actually very close by.
Why BFS won't work
Well, that's not entirely true, one can use BFS (see next subsection), but you cannot use your formula. Take the following graph:
No fancy picture for this graph yet.
Every "o" is a node.
o---o
| |
+-------o---o-------+
| |
o----o----o----o----o
Lets see what levels are possible in BFS. If I start at the node in the middle, I get the following levels:
5~~~5 ~~~ are back-edges
| |
+-------4~~~4-------+
| |
3----2----1----2----3
And if I start at the left node, I get the following levels:
3~~~4
| |
+-------2---3-------+
| |
1----2----3----4~~~~4
Therefore, you cannot use your level formula.
Solution
Although not efficient, using an all-pair shortest path algorithm and checking the distance (i,i) for every node is a valid solution.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…