What is Breadth First Search?
Breadth-first search (BFS) is an algorithm for traversing tree or graph data structures. It starts at the root and explores all the neighboring nodes at the current depth before moving on to nodes at the next depth level.
Implementation
The implementation of BFS may vary depending on the problem. The main idea of BFS is:
- It has a
visitedarray that collects all elements that have already been visited. - It has a
queuewith all elements it’s going to visit. - It loops through the
queue, removes the first element, and appends it to thevisitedlist. - Finally, it loops through all the
neighborsand appends the neighbor to thequeueif it has not been visited and is not already in the queue.
Code Example
func bfs(_ value: String) -> [String] {
let graph: [String: [String]] = [
"New York": ["Buenos Aires", "Cairo", "Tokyo", "London"]
]
var visited: [String] = []
var queue: [String] = []
queue.append(value)
while !queue.isEmpty {
let tmp = queue.removeFirst()
visited.append(tmp)
if let neighbors = graph[tmp] {
for neighbor in neighbors.sorted() {
if !visited.contains(neighbor) && !queue.contains(neighbor) {
queue.append(neighbor)
}
}
}
}
return visited
}