0

Where are the edge lengths are positive and it has to run in O(V^3) time. I'm having a bit of trouble trying to wrap my head around this problem, but this is what I have right now:

Set a shortest cycle variable, make it really large. Loop through every vertex in the graph, then loop through every vertex in the graph for that for loop, then inside the double for loop, I compute the distance from the first vertex to the second, then the second to the first, then compare this distance with my shortest cycle variable and update if it is smaller.

With this implementation then, since I go through every vertex for every vertex in a double for loop it's O(V^3) but I use Djisktra's algorithm twice inside each iteration of the double for loop so that's O(ElogV). I'm not exactly sure how this would be O(V^3) so I think my implementation may need more work.

Coco Loco
  • 1
  • 3

1 Answers1

0

For an O(V³) implementation, you could check if every 3 vertices make a cycle and return those with a minimal total weight:

int minimalCycleWeight = POSITIVE_INFINITY;
// declare nodes to be returned if needed

for (int i = 0; i < verticesCount; i++) {
    for (int j = 0; j < verticesCount; j++) {
        for (int k = 0; k < verticesCount; k++) {
            if (graph[i].hasEdgeTo(graph[j]) 
                && graph[j].hasEdgeTo(graph[k])
                && graph[k].hasEdgeTo(graph[i])) {

                int totalCycleWeight = graph[i].weightTo(graph[j])
                                        + graph[j].weightTo(graph[k])
                                        + graph[k].weightTo(graph[i]);

                if (totalCycleWeight < minimalCycleWeight) { 
                    minimalCycleWeight = totalCycleWeight;
                    // save nodes to return later if needed
                }
            }
        }
    }
}

With Dijkstra's algorithm you could only do better than O(V³).

PajLe
  • 791
  • 1
  • 7
  • 21