Skip to content

Commit

Permalink
Fix infinite recursion in DFS
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
litso authored Nov 4, 2019
1 parent 20bd018 commit 7b08311
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion Topological Sort/TopologicalSort1.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
extension Graph {
private func depthFirstSearch(_ source: Node, visited: inout [Node : Bool]) -> [Node] {
var result = [Node]()
visited[source] = true

if let adjacencyList = adjacencyList(forNode: source) {
for nodeInAdjacencyList in adjacencyList {
Expand All @@ -10,7 +11,6 @@ extension Graph {
}
}

visited[source] = true
return [source] + result
}

Expand Down

0 comments on commit 7b08311

Please sign in to comment.