Chapter 40: Depth-First Search
Last updated
Last updated
extension Graph where Element: Hashable {
func depthFirstSearch(from source: Vertex<Element>) -> [Vertex<Element>] {
// 跟BFS利用queue不同,DFS是利用stack
var stack: Stack<Vertex<Element>> = []
// 記錄目前push到stack的元素
// pushed remembers which vertices have been pushed before so that you don’t visit the same vertex twice. It is a Set to ensure fast O(1) lookup.
var pushed: Set<Vertex<Element>> = []
// 記錄拜訪的順序
var visted: [Vertex<Element>] = []
stack.push(source)
pushed.insert(source)
visted.append(source)
// 終止條件
outer: while let vertex = stack.peek() {
let neighbors = edges(from: vertex)
guard !neighbors.isEmpty else {
// 若找不到任何neighbor, 表示走到盡頭
stack.pop()
continue
}
for edge in neighbors {
if !pushed.contains(edge.destination) {
// 尚未被拜訪過
stack.push(edge.destination)
pushed.insert(edge.destination)
visted.append(edge.destination)
// Now that you’ve found a neighbor to visit, you continue the outer loop and move to the newly pushed neighbor.
continue outer
}
}
// If the current vertex did not have any unvisited neighbors, you know you’ve reached a dead end and can pop it off the stack.
stack.pop()
}
return visted
}
}