This page provides a comprehensive guide on how to implement Depth First Search (DFS) and Breadth First Search (BFS) algorithms in Swift.
Swift, DFS, BFS, Depth First Search, Breadth First Search, Algorithms, Data Structures
import Foundation
class Graph {
var adjList: [Int: [Int]] = [:]
func addEdge(from source: Int, to destination: Int) {
if adjList[source] != nil {
adjList[source]?.append(destination)
} else {
adjList[source] = [destination]
}
// For undirected graph (if needed)
if adjList[destination] != nil {
adjList[destination]?.append(source)
} else {
adjList[destination] = [source]
}
}
// Depth First Search
func dfs(start: Int) {
var visited = Set()
dfsHelper(node: start, visited: &visited)
}
private func dfsHelper(node: Int, visited: inout Set) {
visited.insert(node)
print(node)
guard let neighbors = adjList[node] else { return }
for neighbor in neighbors {
if !visited.contains(neighbor) {
dfsHelper(node: neighbor, visited: &visited)
}
}
}
// Breadth First Search
func bfs(start: Int) {
var visited = Set()
var queue: [Int] = [start]
visited.insert(start)
while !queue.isEmpty {
let node = queue.removeFirst()
print(node)
guard let neighbors = adjList[node] else { continue }
for neighbor in neighbors {
if !visited.contains(neighbor) {
visited.insert(neighbor)
queue.append(neighbor)
}
}
}
}
}
// Example of usage
let graph = Graph()
graph.addEdge(from: 1, to: 2)
graph.addEdge(from: 1, to: 3)
graph.addEdge(from: 2, to: 4)
graph.addEdge(from: 3, to: 5)
print("DFS:")
graph.dfs(start: 1)
print("BFS:")
graph.bfs(start: 1)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?