문제 링크 (opens new window)

# 풀이

  1. 넓이 구하기 - visited 부터 한칸 넓이 계산해서 재귀함수 종료 이후 리턴된 넓이값을 더해서 최종리턴
import Foundation

let mnk = readLine()!.split(separator: " ").map { Int($0)! }; let m = mnk[0]; let n = mnk[1]; let k = mnk[2]

var adj: [[Int]] = .init(repeating: .init(repeating: 0, count: n), count: m)
var visited: [[Bool]] = .init(repeating: .init(repeating: false, count: n), count: m)

let dy = [-1, 0, 1, 0]; let dx = [0, 1, 0, -1]
var ret = 0

for _ in 0..<k {
    let square = readLine()!.split(separator: " ").map { Int($0)! }
    for row in square[1]..<square[3] {
        for col in square[0]..<square[2] {
            adj[row][col] = 1
        }
    }
}

func dfs(_ y: Int, _ x: Int) -> Int {
    visited[y][x] = true
    var area = 1
    for i in 0..<4 {
        let ny = dy[i] + y
        let nx = dx[i] + x

        if ny < 0 || nx < 0 || ny >= m || nx >= n {
            continue
        }

        if visited[ny][nx] || adj[ny][nx] == 1 {
            continue
        }

        area += dfs(ny, nx)
    }
    return area
}

var results:[Int] = []

for row in 0..<m {
    for col in 0..<n {
        if visited[row][col] || adj[row][col] == 1 {
            continue
        }

        results.append(dfs(row, col))
        ret += 1
    }
}

print(ret)
results.sorted().forEach { print($0, terminator: " ")}