How do I implement DFS and BFS in Swift?

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)

Swift DFS BFS Depth First Search Breadth First Search Algorithms Data Structures