문제 링크 (opens new window)

# 풀이

  1. 열거형 활용하여 코드 가독성 확보
import Foundation

let n = Int(readLine()!)!
var tree: [[Int]] = .init(repeating: .init(repeating: 0, count: n), count: n)

for i in 0..<n {
    tree[i] = readLine()!.map { Int(String($0))! }
}

enum Position {
    case leftTop
    case rightTop
    case leftBottom
    case rightBottom
}

func solution(_ pos: Position, _ start: (Int, Int), _ length: Int) -> String {
    if length == 1 {
        return "\(tree[start.0][start.1])"
    }

    var result = "("

    result += solution(.leftTop, (start.0, start.1), length / 2)
    result += solution(.rightTop, (start.0, start.1 + length / 2), length / 2)
    result += solution(.leftBottom, (start.0 + length / 2, start.1), length / 2)
    result += solution(.rightBottom, (start.0 + length / 2, start.1 + length / 2), length / 2)

    result += ")"

    // 괄호로 둘러쌓인 문자열이 0이나 1로만 이루어진 경우 -> 압축
    let firstChar = result[result.index(result.startIndex, offsetBy: 1)]
    var isQuadtree = true

    for char in result {
        if char == "(" || char == ")" {
            continue
        }

        if char != firstChar {
            isQuadtree = false
        }
    }

    if isQuadtree {
        result = String(firstChar)
    }

    return result
}

print(solution(.leftTop, (0,0), n))