Swift Data Structure And Algorithm/Graph Algorithm

๋‹จ์ง€ ๋ฒˆํ˜ธ ๋ถ™์ด๊ธฐ_DFS

youngjaeLee1026 2022. 4. 15. 11:44

1. ๋ฌธ์ œ

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-04-15 11 36 03

2. ์ž…์ถœ๋ ฅ

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

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

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-04-15 11 36 23

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

  • ๊ทธ๋ฆผ 1 ์ฒ˜๋Ÿผ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” 2์ฐจ์› ๋ฐฐ์—ด์„ ๊ทธ๋ž˜ํ”„๋ผ๊ณ  ๊ฐ€์ •ํ•˜๊ณ , ํ˜„์žฌ ์›์†Œ๊ฐ€ 1์ด๋ผ๋ฉด ์ƒ, ํ•˜, ์ขŒ, ์šฐ ๋ฐฉํ–ฅ์œผ๋กœ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰(DFS or BFS)์„ ์ง„ํ–‰ํ•˜๊ณ , ๋”์ด์ƒ ์ƒ, ํ•˜, ์ขŒ, ์šฐ์— ์ธ์ ‘ํ•œ ์›์†Œ 1์ด ์—†๋‹ค๋ฉด ํƒ์ƒ‰์„ ๋ฉˆ์ถ”๊ณ  ๊ทธ ๋•Œ์˜ count ๊ฐ’์„ ๋ณ„๋„์˜ ๋ฐฐ์—ด ํ˜น์€ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ
  • ์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ, 2์ฐจ์› ๋ฐฐ์—ด์˜ ์ž…๋ ฅ์— ์ฃผ์˜ํ•ด์•ผ ํ•˜๋Š”๋ฐ, ํ•œ ์ค„ ๋‹จ์œ„๋กœ ์ž…๋ ฅ์„ ๋ฐ›๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋ฌธ์ž์—ด์— ๊ฐ๊ฐ์˜ ์›์†Œ๋ฅผ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐฐ์—ด์„ ๊ตฌ์„ฑํ•ด์•ผ ํ•จ
  • ๋งˆ์ง€๋ง‰์œผ๋กœ, count ๊ฐ’์„ ๋‹ด์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•˜๊ณ , ๋ฆฌ์ŠคํŠธ์˜ ํฌ๊ธฐ์™€ ์›์†Œ๋ฅผ ์ฐจ๋ก€๋กœ ์ถœ๋ ฅํ•จ์œผ๋กœ์จ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ

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

//MARK: - ๋‹จ์ง€ ๋ฒˆํ˜ธ ๋ถ™์ด๊ธฐ

//MARK: - Framework
import Foundation

//MARK: - Variable
var graph: [[Int]] = []
var visited: [[Bool]] = []
var count: Int = 0

//MARK: - Function
func dfs(_ x: Int, _ y: Int) -> Void {
    let dx: [Int] = [-1, 1, 0, 0]
    let dy: [Int] = [0, 0, -1, 1]
    
    visited[x][y] = true
    count += 1
    
    for i in 0..<dx.count {
        let nx: Int = x + dx[i]
        let ny: Int = y + dy[i]
        
        if graph[nx][ny] == 1 && !visited[nx][ny] {
            dfs(nx, ny)
        }
    }
}

func solution() -> Void {
    //MARK: - Input
    guard let N: Int = Int(readLine() ?? "0") else { return }
    var homeCounts: [Int] = []
    graph = Array(repeating: Array(repeating: 0, count: N + 10), count: N + 10)
    visited = Array(repeating: Array(repeating: false, count: N + 10), count: N + 10)
    
    for i in 1...N {
        guard let str: String = readLine() else { return }
        for j in 0..<str.count {
            graph[i][j + 1] = Int("\(str[str.index(str.startIndex, offsetBy: j)])") ?? 0
        }
    }
    
    //MARK: - Process
    for i in 1...N {
        for j in 1...N {
            if graph[i][j] == 1 && !visited[i][j] {
                dfs(i, j)
                homeCounts.append(count)
                count = 0
            }
        }
    }
    homeCounts.sort { $0 < $1 }
    
    //MARK: - Output
    print(homeCounts.count)
    for count in homeCounts {
        print(count)
    }
}
solution()

 

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