Created
August 27, 2019 01:24
-
-
Save davidinga/2fb7ffb1903b9164d07e06e6fd0ac425 to your computer and use it in GitHub Desktop.
Depth First Search (DFS) implementation in Swift. Uses my GraphOP and Stack objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func depthFirstSearch(from start: Vertex<String>, | |
to end: Vertex<String>, | |
in graph: GraphOP<String> ) -> Stack<Vertex<String>> { | |
var stack = Stack<Vertex<String>>() | |
var visited = Set<Vertex<String>>() | |
stack.push(start) | |
visited.insert(start) | |
outer: while let vertex = stack.peek(), vertex != end { | |
guard let neighbors = graph.edges(from: vertex), neighbors.count > 0 else { | |
stack.pop() | |
continue | |
} | |
for edge in neighbors { | |
if !visited.contains(edge.destination) { | |
stack.push(edge.destination) | |
visited.insert(edge.destination) | |
continue outer | |
} | |
} | |
stack.pop() | |
} | |
return stack | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment