๐Ÿ“ ์ฝ”ํ…Œ/BOJ

[Swift] ๋ฐฑ์ค€ 10026 ์ ๋ก์ƒ‰์•ฝ

JerryiOS 2023. 4. 14. 02:41

import Foundation

let N = Int(readLine()!)!

var board = [[String]]()

let dx = [0, 0, -1, 1]
let dy = [-1, 1, 0, 0]    // ์ƒํ•˜์ขŒ์šฐ

var cnts = [0, 0]

for _ in 0..<N {
    let colors = readLine()!.map { String($0) }
    board.append(colors)
}

func dfs(_ x: Int, _ y: Int, _ color: String) {
    board[x][y] = ""
    
    for i in 0..<4 {
        let nx = x + dx[i]
        let ny = y + dy[i]
        
        if nx>=0, nx<N, ny>=0, ny<N, !board[nx][ny].isEmpty {
            let nColor = board[nx][ny]
            
            if nColor == color {
                dfs(nx, ny, nColor)
            } else if nColor.isEmpty {
                return
            }
        }
    }
}

func getCnt1() {
    for i in 0..<N {
        for j in 0..<N {
            if !board[i][j].isEmpty {
                dfs(i, j, board[i][j])
                cnts[0] += 1
            }
        }
    }
}

func getCnt2() {
    for i in 0..<N {
        for j in 0..<N {
            if !board[i][j].isEmpty {
                dfs(i, j, board[i][j])
                cnts[1] += 1
            }
        }
    }
}

let board2 = board

getCnt1()
board = board2.map({ strArr in
    strArr.map { str in
        if str == "G" {
            return "R"
        } else {
            return str
        }
    }
})
getCnt2()
print(cnts[0], cnts[1])

์œ ๊ธฐ๋† ๋ฐฐ์ถ” ๋ฌธ์ œ์ฒ˜๋Ÿผ DFS๋กœ ํ’€์—ˆ๋‹ค.

๋ฐ˜์‘ํ˜•