Chapter 38: Breadth-First Search
Last updated
Last updated
extension Graph where Element: Hashable {
func breadFirstSearch(from source: Vertex<Element>) -> [Vertex<Element>] {
// 紀錄接下來要拜訪的鄰居
var queue = QueueStack<Vertex<Element>>()
// enqueued remembers which vertices have been enqueued before so you don’t enqueue the same vertex twice. You use a Set type here so that lookup is cheap and only takes O(1).
var enqueued: Set<Vertex<Element>> = []
// 記錄拜訪的順序
var visited: [Vertex<Element>] = []
queue.enqueue(source)
enqueued.insert(source)
while let vertex = queue.dequeue() {
visited.append(vertex)
// 取出下一層的鄰居們
let neighborEdges = edges(from: vertex)
neighborEdges.forEach { edge in
if !enqueued.contains(edge.destination) {
// 表示這個點尚未被加入queue中
queue.enqueue(edge.destination)
enqueued.insert(edge.destination)
}
}
}
return visited
}
}