Skip to content

Commit efd8c37

Browse files
committed
Don't call indexOfVertex(head) per neighbor.
Reduces the cycle detection complexity from O(V²) to O(V). indexOfVertex(head) takes O(V) time, and if we call it `neighbors` times (O(V)) then we end up with the O(V²) time complexity of the cycle detection. To fix this, we only need to move the head vertex index lookup to the outside of the loop.
1 parent d1de55a commit efd8c37

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

Sources/SwiftGraph/Cycle.swift

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,15 @@ public extension Graph {
3535
while openPaths.count > 0 {
3636
let openPath = openPaths.removeFirst() // queue pop()
3737
if openPath.count > maxK { return cycles } // do we want to stop at a certain length k
38-
if let tail = openPath.last, let head = openPath.first, let neighbors = neighborsForVertex(tail) {
38+
if let tail = openPath.last,
39+
let head = openPath.first,
40+
let headIndex = indexOfVertex(head),
41+
let neighbors = neighborsForVertex(tail) {
3942
for neighbor in neighbors {
4043
if neighbor == head {
4144
cycles.append(openPath + [neighbor]) // found a cycle
42-
} else if !openPath.contains(neighbor) && indexOfVertex(neighbor)! > indexOfVertex(head)! {
45+
} else if let neighborIndex = indexOfVertex(neighbor),
46+
!openPath.contains(neighbor) && neighborIndex > headIndex {
4347
openPaths.append(openPath + [neighbor]) // another open path to explore
4448
}
4549
}

0 commit comments

Comments
 (0)