Shortest Cycle Detection
Directed Graphs
Positive Weights
Graph Algorithms
Cycle Finding

Find cycle of shortest length in a directed graph with positive weights

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding the cycle of shortest length in a directed graph with positive weights is an important problem in graph theory and algorithms. It appears in networks where you need to detect the smallest feedback loop, such as routing cycles in networks, deadlock detection in resource allocation graphs, or identifying the shortest periodic pattern in a state machine. The challenge is to find a cycle (a path that returns to its starting node) whose total edge weight is minimized.

Problem Definition

Given a directed graph G=(V,E)G = (V, E) where VV is a set of vertices and EE is a set of directed edges, each edge (u,v)(u, v) has a positive weight w(u,v)>0w(u, v) > 0. The goal is to find a cycle v0v1vkv0v_0 \to v_1 \to \ldots \to v_k \to v_0 such that the total weight i=0kw(vi,v(i+1)mod(k+1))\sum_{i=0}^{k} w(v_i, v_{(i+1) \bmod (k+1)}) is minimized over all cycles in the graph.

Key Concepts

Graph Representation

A directed graph can be represented using an adjacency matrix or an adjacency list.

  • Adjacency matrix: A 2D array where entry W[u][v]W[u][v] stores the weight of edge (u,v)(u, v), or \infty if no edge exists.
  • Adjacency list: Each vertex stores a list of its outgoing edges and their weights. More memory-efficient for sparse graphs.

Why Positive Weights Matter

Positive weights guarantee that no negative-weight cycle exists. This is important because algorithms like Floyd-Warshall and Dijkstra rely on this property for correctness. With positive weights, every cycle has a strictly positive total weight, and the shortest cycle is well-defined.

Algorithmic Approaches

Approach 1: Floyd-Warshall Adaptation

The Floyd-Warshall algorithm computes shortest paths between all pairs of vertices. We can adapt it to find the shortest cycle.

Initialization: Set up a distance matrix DD where D[u][v]=w(u,v)D[u][v] = w(u, v) if edge (u,v)(u, v) exists, and D[u][v]=D[u][v] = \infty otherwise. Crucially, set D[u][u]=D[u][u] = \infty (not zero) because we want the shortest path from uu back to uu through at least one other vertex.

Distance Update: Apply the standard triple-nested loop:

D[i][j]=min(D[i][j],D[i][k]+D[k][j])D[i][j] = \min(D[i][j], D[i][k] + D[k][j])

for each intermediate vertex kk.

Shortest Cycle: After the algorithm completes, the shortest cycle length is:

minvVD[v][v]\min_{v \in V} D[v][v]

The minimum diagonal entry gives the weight of the shortest cycle.

Complexity: O(V3)O(|V|^3) time and O(V2)O(|V|^2) space. This is practical for dense graphs with moderate vertex counts.

Approach 2: Dijkstra from Each Vertex

For sparse graphs, running Dijkstra's algorithm from each vertex can be more efficient.

For each vertex uu:

  1. Run Dijkstra's shortest path from uu.
  2. For each incoming edge (v,u)(v, u) with weight w(v,u)w(v, u), compute dist(u,v)+w(v,u)dist(u, v) + w(v, u). This gives the shortest cycle through uu that uses edge (v,u)(v, u) as its final edge.
  3. Track the minimum across all vertices.

Complexity: O(V(ElogV))O(|V| \cdot (|E| \log |V|)) with a binary heap. For sparse graphs where EV2|E| \ll |V|^2, this beats Floyd-Warshall.

Approach 3: DFS-Based Cycle Detection with Weight Tracking

A depth-first search can find cycles by detecting back edges. During DFS, maintain a stack of vertices in the current path along with cumulative weights. When a back edge is found (an edge to a vertex already on the current stack), compute the cycle weight as the difference in cumulative weights plus the back edge weight.

This approach does not guarantee finding the globally shortest cycle in a single pass, but it can be used as a heuristic or combined with iterating over all starting vertices.

Worked Example

Consider a directed graph with these weighted edges:

FromToWeight
AB1
BC2
CA1
CD3
DB4

Cycles in this graph:

  1. A to B to C to A: weight = 1+2+1=41 + 2 + 1 = 4
  2. B to C to D to B: weight = 2+3+4=92 + 3 + 4 = 9

Using Floyd-Warshall, initialize the distance matrix with edge weights and \infty on the diagonal:

ABCD
A\infty1\infty\infty
B\infty\infty2\infty
C1\infty\infty3
D\infty4\infty\infty

After running the algorithm, the diagonal entries become: D[A][A]=4D[A][A] = 4, D[B][B]=9D[B][B] = 9, D[C][C]=4D[C][C] = 4, D[D][D]=9D[D][D] = 9. The shortest cycle has weight min(4,9,4,9)=4\min(4, 9, 4, 9) = 4, which corresponds to A to B to C to A.

Comparison of Approaches

ApproachTime ComplexityBest For
Floyd-Warshall`$O(V^3)$`Dense graphs, small to medium `$V$`
Dijkstra per vertex`$O(V\cdotE\logV)$`Sparse graphs
DFS-based`$O(V+E)$` per runHeuristic or when any cycle suffices

Practical Considerations

  • No cycle exists: If the graph is a DAG (directed acyclic graph), there are no cycles. Floyd-Warshall will leave all diagonal entries at \infty, and Dijkstra will never find a path from any vertex back to itself.
  • Reconstructing the cycle: To find the actual vertices in the shortest cycle (not just the weight), maintain a predecessor matrix during Floyd-Warshall or a predecessor array during Dijkstra. Trace back from the diagonal entry to reconstruct the path.
  • Self-loops: A self-loop (v,v)(v, v) with weight ww is technically a cycle of length 1. If self-loops should be excluded, skip diagonal entries that come directly from a single edge.

Summary

Finding the shortest cycle in a directed graph with positive weights can be solved by adapting Floyd-Warshall (set diagonal to \infty initially, then read the minimum diagonal entry after completion) or by running Dijkstra from each vertex and checking for paths back to the source. Floyd-Warshall is simpler to implement and works well for dense graphs at O(V3)O(|V|^3), while the Dijkstra approach scales better for sparse graphs. Both approaches are correct because positive edge weights guarantee no negative cycles.


Course illustration
Course illustration

All Rights Reserved.