- Notice it's a directed graph with weighted edges.
- Run Dijkstra's Algorithm from node
s
to give us the shortest path to every other node. If the edges weren't weighted, we could simply use BFS instead. - Let
N
be the set of vertices in our graph.n
be 1 node inN
.dijkstraDistance(s, n)
be the shortest distance from nodes
ton
without using the edge between them (since that edge is directed fromn
tos
)lengthOfDirectedEdge(n, s)
be the length of the directed edge from noden
to nodes
. If such an edge doesn't exist, let this function return infinity.
- Shortest cycle is: For every
n
inN
, the minimum value ofdijkstraDistance(s, n) + lengthOfDirectedEdge(n, s)
. Notice this formula should only be used if an edge fromn
tos
exists.
- Time Complexity:
O(m + n log n)
to run Dijkstra's algorithm. - Space Complexity:
O(n)
due to Dijkstra's algorithm