Skip to content

Commit 7b08311

Browse files
authoredNov 4, 2019
Fix infinite recursion in DFS
Fixes infinite recursion in the DFS algorithm for topological sort caused by graphs with cycles. For example the following graph would previously have recursed indefinitely `a->b->a`.
1 parent 20bd018 commit 7b08311

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed
 

‎Topological Sort/TopologicalSort1.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
extension Graph {
22
private func depthFirstSearch(_ source: Node, visited: inout [Node : Bool]) -> [Node] {
33
var result = [Node]()
4+
visited[source] = true
45

56
if let adjacencyList = adjacencyList(forNode: source) {
67
for nodeInAdjacencyList in adjacencyList {
@@ -10,7 +11,6 @@ extension Graph {
1011
}
1112
}
1213

13-
visited[source] = true
1414
return [source] + result
1515
}
1616

0 commit comments

Comments
 (0)