I was asked this question in an interview, but I couldn't come up with any decent solution. So, I told them the naive approach of finding all the cycles then picking the cycle with the least length.
I'm curious to know what is an efficient solution to this problem.
We can also use branch and bound algorithm for travelling salesman problem, as your question matches with TSP. http://lcm.csa.iisc.ernet.in/dsa/node187.html
You can easily modify Floyd-Warshall algorithm. (If you're not familiar with graph theory at all, I suggest checking it out, e.g. getting a copy of Introduction to Algorithms).
Traditionally, you start
path[i][i] = 0
for eachi
. But you can instead start frompath[i][i] = INFINITY
. It won't affect algorithm itself, as those zeroes weren't used in computation anyway (since pathpath[i][j]
will never change fork == i
ork == j
).In the end,
path[i][i]
is the length the shortest cycle going throughi
. Consequently, you need to findmin(path[i][i])
for alli
. And if you want cycle itself (not only its length), you can do it just like it's usually done with normal paths: by memorizingk
during execution of algorithm.In addition, you can also use Dijkstra's algorithm to find a shortest cycle going through any given node. If you run this modified Dijkstra for each node, you'll get the same result as with Floyd-Warshall. And since each Dijkstra is
O(n^2)
, you'll get the sameO(n^3)
overall complexity.What you will have to do is to assign another weight to each node which is always 1. Now run any shortest path algorithm from one node to the same node using these weights. But while considering the intermediate paths, you will have to ignore the paths whose actual weights are negative.
Below is a simple modification of Floyd - Warshell algorithm.
The pseudo code is a simple modification of Dijkstra's algorithm.
Time Complexity: O(|V|^3)
Tree Edge
,Back Edge
,Down Edge
andParent Edge
Back Edge
and have another counter for getting length.See
Algorithms in C++ Part5 - Robert Sedgwick
for more details