Swift Data Structure And Algorithm/Graph Algorithm

๊นŠ์ด์šฐ์„ ํƒ์ƒ‰๊ณผ ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰

youngjaeLee1026 2022. 4. 15. 13:10

1. ๋ฌธ์ œ

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-04-15 13 14 54

2. ์ž…์ถœ๋ ฅ

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-04-15 13 15 02

3. ์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-04-15 13 15 10

4. ๋ฌธ์ œ ์„ค๊ณ„

  • ์œ„ ๋ฌธ์ œ์—์„œ๋Š” ์กฐ์‹ฌํ•ด์•ผ ํ•˜๋Š” ๋ถ€๋ถ„์ด ์˜ˆ์‹œ ์ž…๋ ฅ์—๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ž…๋ ฅ์ด ๋˜์ง€๋งŒ ๊ณ„์† ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ž…๋ ฅ ๋œ๋‹ค๋Š” ๋ณด์žฅ์ด ์—†๊ธฐ ๋•Œ๋ฌธ์—
  • ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ์ „์— ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•ด์ฃผ๋Š” ์ž‘์—…์ด ํ•„์š”ํ•จ.

5. ์ „์ฒด ์ฝ”๋“œ

//MARK: - ๊นŠ์ด์šฐ์„ ํƒ์ƒ‰๊ณผ ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰

//MARK: - Framework
import Foundation

//MARK: - Type
struct Graph {
    //MARK: - Property
    var edges: [Int]
    
    //MARK: - Initializer
    init() {
        self.edges = []
    }
}

//MARK: - Vairable
var graph: [Graph] = []
var visited: [Bool] = []

//MARK: - Function
func dfs(_ x: Int) -> Void {
    visited[x] = true;
    print("\(x) ", terminator: "")
    
    for i in stride(from: 0, to: graph[x].edges.count, by: 1) {
        let y: Int = graph[x].edges[i]
        
        if !visited[y] {
            visited[y] = true
            dfs(y)
        }
    }
}

func bfs(_ start: Int) -> Void {
    var queue: [Int] = []
    queue.append(start)
    visited[start] = true
    
    while !queue.isEmpty {
        let current: Int = queue.removeFirst()
        print("\(current) ", terminator: "")
        
        for i in stride(from: 0, to: graph[current].edges.count, by: 1) {
            let next: Int = graph[current].edges[i]
            
            if !visited[next] {
                visited[next] = true
                queue.append(next)
            }
        }
    }
}

func solution() -> Void {
    //MARK: - Input
    guard let input: [String] = readLine()?.components(separatedBy: " ") else { return }
    let N: Int = input.map { Int($0) }[0] ?? 0
    let M: Int = input.map { Int($0) }[1] ?? 0
    graph = Array(repeating: Graph(), count: N + 10)
    visited = Array(repeating: false, count: N + 10)
    
    for _ in 0..<M {
        guard let data: [String] = readLine()?.components(separatedBy: " ") else { return }
        let a: Int = data.map { Int($0) }[0] ?? 0
        let b: Int = data.map { Int($0) }[1] ?? 0
        
        graph[a].edges.append(b)
        graph[b].edges.append(a)
    }
    
    //MARK: - Process & Output
    for i in 0..<N {
        graph[i].edges.sort { $0 < $1 }
    }
    
    dfs(0)
    
    visited = Array(repeating: false, count: N + 10)
    print()
    
    bfs(0)
}
solution()

 

์ „์ฒด์ฝ”๋“œ๋Š” ์—ฌ๊ธฐ์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.