문제 링크 (opens new window)

# 풀이

import Foundation

let t = Int(readLine()!)!
var result: [Int] = []

for _ in 0..<t {
    // n * m
    let nmk = readLine()!.split(separator: " ").map { Int($0)! }; let n = nmk[0]; let m = nmk[1]; let k = nmk[2]
    var adj: [[Int]] = .init(repeating: .init(repeating: 0, count: 54), count: 54)
    var visited: [[Bool]] = .init(repeating: .init(repeating: false, count: 54), count: 54)

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

    for i in 0..<k {
        let pos = readLine()!.split(separator: " ").map { Int($0)! }; let ypos = pos[0]; let xpos = pos[1]
        adj[ypos][xpos] = 1
    }


    func dfs(_ y: Int, _ x: Int) {
        visited[y][x] = true

        for i in 0..<4 {
            let ny = dy[i] + y
            let nx = dx[i] + x

            if ny < 0 || nx < 0 || ny >= n || nx >= m || visited[ny][nx] || adj[ny][nx] == 0 { continue }
            dfs(ny, nx)
        }
    }

    for i in 0..<n {
        for j in 0..<m {
            if adj[i][j] == 0 || visited[i][j] {
                continue
            }
            dfs(i, j)
            ret += 1
        }
    }

    result.append(ret)
}

for i in result {
    print(i)
}