Swift Data Structure And Algorithm/Graph Algorithm

2์ƒ‰์น ํ•˜๊ธฐ_BFS

youngjaeLee1026 2022. 4. 15. 13:11

1. ๋ฌธ์ œ

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

2. ์ž…์ถœ๋ ฅ

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

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

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

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

  • ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋กœ ๊ทธ๋ž˜ํ”„๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ , ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜๋ฉด์„œ ๊ฐ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•  ๋•Œ๋งˆ๋‹ค ์ธ์ ‘ํ•œ ๋…ธ๋“œ์˜ ์ƒ‰์ด 0์ด๋ผ๋ฉด 1, 1์ด๋ผ๋ฉด 0์„ ์น ํ•จ
  • ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค์— ๋Œ€ํ•œ ์ƒ‰์น ์„ ๋งˆ์น˜๊ณ , ํ˜„์žฌ๋…ธ๋“œ์™€ ์ธ์ ‘ํ•œ ๋…ธ๋“œ ์ค‘ ๊ฐ™์€ ์ƒ‰์ด ์žˆ์œผ๋ฉด 2์ƒ‰ ์ƒ‰์น ํ•˜๊ธฐ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Œ
  • ๋”ฐ๋ผ์„œ O(N + M)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ

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

//MARK: - 2์ƒ‰์น ํ•˜๊ธฐ - BFS

//MARK: - Framework
import Foundation

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

//MARK: - Variable
var graph: [Graph] = []
var visited: [Bool] = []
var groups: [Int] = []

//MARK: - Function
func bfs(_ start: Int) -> Bool {
    var result: Bool = true
    var queue: [Int] = []
    queue.append(start)
    visited[start] = true
    
    while !queue.isEmpty {
        let current: Int = queue.removeFirst()
        
        for i in stride(from: 0, to: graph[current].edges.count, by: 1) {
            let next: Int = graph[current].edges[i]
            
            if !visited[next] {
                groups[next] = groups[current] == 0 ? 1 : 0
                visited[next] = true
                queue.append(next)
            }
            
            if groups[next] == groups[current] {
                result = false
                break
            }
        }
        
        if !result {
            break
        }
    }
    
    return result
}

func solution() -> Void {
    //MARK: - Input
    guard let input = 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)
    groups = Array(repeating: 0, count: N + 10)
    
    for _ in 0..<M {
        guard let data = 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
    print(bfs(0) ? "YES" : "NO")
}
solution()

 

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