Skip to content

Instantly share code, notes, and snippets.

@alexpersian
Created December 9, 2019 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpersian/3334d549ab4a681748922bc91fbd4f45 to your computer and use it in GitHub Desktop.
Save alexpersian/3334d549ab4a681748922bc91fbd4f45 to your computer and use it in GitHub Desktop.
Graph + DepthFirstSearch
import Foundation
final class DepthFirstSearch<T: Hashable> {
private let graph: Graph<T>
private var searchStack: [T] = []
private var visited: Set<T> = Set()
init(graph: Graph<T>) {
self.graph = graph
}
func contains(_ value: T) -> Bool {
searchStack.append(graph.storage.first!.key)
while let vertex = searchStack.popLast() {
if vertex == value { return true }
if !visited.contains(vertex) {
searchStack.append(contentsOf: graph.getEdges(for: vertex) ?? [])
visited.insert(vertex)
} else {
continue
}
}
return false
}
}
final class Graph<T: Hashable> {
private(set) var storage: [T: Set<T>]
init(vertices: [T]) {
storage = [:]
vertices.forEach { storage[$0] = Set() }
}
func addEdge(between v: T, and w: T) {
guard storage[v] != nil && storage[w] != nil else { return }
storage[v]?.insert(w)
storage[w]?.insert(v)
}
func addEdges(_ edges: [T], to vertex: T) {
edges.forEach { addEdge(between: vertex, and: $0) }
}
func getEdges(for vertex: T) -> Set<T>? {
return storage[vertex]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment