forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 1
/
TopologicalSort1.swift
38 lines (31 loc) · 988 Bytes
/
TopologicalSort1.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
36
37
38
extension Graph {
private func depthFirstSearch(_ source: Node, visited: inout [Node : Bool]) -> [Node] {
var result = [Node]()
if let adjacencyList = adjacencyList(forNode: source) {
for nodeInAdjacencyList in adjacencyList {
if let seen = visited[nodeInAdjacencyList], !seen {
result = depthFirstSearch(nodeInAdjacencyList, visited: &visited) + result
}
}
}
visited[source] = true
return [source] + result
}
/* Topological sort using depth-first search. */
public func topologicalSort() -> [Node] {
let startNodes = calculateInDegreeOfNodes().filter({ _, indegree in
return indegree == 0
}).map({ node, _ in
return node
})
var visited = [Node: Bool]()
for (node, _) in adjacencyLists {
visited[node] = false
}
var result = [Node]()
for startNode in startNodes {
result = depthFirstSearch(startNode, visited: &visited) + result
}
return result
}
}