Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of topological sort #79

Merged
merged 1 commit into from
Mar 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 15 additions & 9 deletions Sources/SwiftGraph/Sort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,27 @@ public extension Graph {
/// - returns: the sorted vertices, or nil if the graph cannot be sorted due to not being a DAG
func topologicalSort() -> [V]? {
var sortedVertices = [V]()
let tsNodes = vertices.map{ TSNode<V>(vertex: $0, color: .white) }
let rangeOfVertices = 0..<vertexCount
let tsNodes = rangeOfVertices.map { TSNode(index: $0, color: .white) }
var notDAG = false

// Determine vertex neighbors in advance, so we have to do it once for each node.
var neighbors: [Set<Int>] = rangeOfVertices.map({ index in
Set(edges[index].map({ $0.v }))
})

func visit(_ node: TSNode<V>) {
func visit(_ node: TSNode) {
guard node.color != .gray else {
notDAG = true
return
}
if node.color == .white {
node.color = .gray
for inode in tsNodes where (neighborsForVertex(node.vertex)?.contains(inode.vertex))! {
for inode in tsNodes where neighbors[node.index].contains(inode.index) {
visit(inode)
}
node.color = .black
sortedVertices.insert(node.vertex, at: 0)
sortedVertices.insert(vertices[node.index], at: 0)
}
}

Expand Down Expand Up @@ -71,12 +77,12 @@ public extension Graph {

fileprivate enum TSColor { case black, gray, white }

fileprivate class TSNode<V> {
fileprivate let vertex: V
fileprivate class TSNode {
fileprivate let index: Int
fileprivate var color: TSColor
init(vertex: V, color: TSColor) {
self.vertex = vertex

init(index: Int, color: TSColor) {
self.index = index
self.color = color
}
}