forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TopologicalSort3.swift
35 lines (31 loc) · 930 Bytes
/
TopologicalSort3.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
An alternative implementation of topological sort using depth-first search.
This does not start at vertices with in-degree 0 but simply at the first one
it finds. It uses a stack to build up the sorted list, but in reverse order.
*/
extension Graph {
public func topologicalSortAlternative() -> [Node] {
var stack = [Node]()
var visited = [Node: Bool]()
for (node, _) in adjacencyLists {
visited[node] = false
}
func depthFirstSearch(_ source: Node) {
if let adjacencyList = adjacencyList(forNode: source) {
for neighbor in adjacencyList {
if let seen = visited[neighbor], !seen {
depthFirstSearch(neighbor)
}
}
}
stack.append(source)
visited[source] = true
}
for (node, _) in visited {
if let seen = visited[node], !seen {
depthFirstSearch(node)
}
}
return stack.reversed()
}
}