@@ -29,21 +29,27 @@ public extension Graph {
29
29
/// - returns: the sorted vertices, or nil if the graph cannot be sorted due to not being a DAG
30
30
func topologicalSort( ) -> [ V ] ? {
31
31
var sortedVertices = [ V] ( )
32
- let tsNodes = vertices. map { TSNode < V > ( vertex: $0, color: . white) }
32
+ let rangeOfVertices = 0 ..< vertexCount
33
+ let tsNodes = rangeOfVertices. map { TSNode ( index: $0, color: . white) }
33
34
var notDAG = false
35
+
36
+ // Determine vertex neighbors in advance, so we have to do it once for each node.
37
+ var neighbors : [ Set < Int > ] = rangeOfVertices. map ( { index in
38
+ Set ( edges [ index] . map ( { $0. v } ) )
39
+ } )
34
40
35
- func visit( _ node: TSNode < V > ) {
41
+ func visit( _ node: TSNode ) {
36
42
guard node. color != . gray else {
37
43
notDAG = true
38
44
return
39
45
}
40
46
if node. color == . white {
41
47
node. color = . gray
42
- for inode in tsNodes where ( neighborsForVertex ( node. vertex ) ? . contains ( inode. vertex ) ) ! {
48
+ for inode in tsNodes where neighbors [ node. index ] . contains ( inode. index ) {
43
49
visit ( inode)
44
50
}
45
51
node. color = . black
46
- sortedVertices. insert ( node. vertex , at: 0 )
52
+ sortedVertices. insert ( vertices [ node. index ] , at: 0 )
47
53
}
48
54
}
49
55
@@ -71,12 +77,12 @@ public extension Graph {
71
77
72
78
fileprivate enum TSColor { case black, gray, white }
73
79
74
- fileprivate class TSNode < V > {
75
- fileprivate let vertex : V
80
+ fileprivate class TSNode {
81
+ fileprivate let index : Int
76
82
fileprivate var color : TSColor
77
-
78
- init ( vertex : V , color: TSColor ) {
79
- self . vertex = vertex
83
+
84
+ init ( index : Int , color: TSColor ) {
85
+ self . index = index
80
86
self . color = color
81
87
}
82
88
}
0 commit comments