Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 27, 2019 01:24
Show Gist options
  • Save davidinga/2fb7ffb1903b9164d07e06e6fd0ac425 to your computer and use it in GitHub Desktop.
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.
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