💻 Algorithm/Swift

[Swift] 백준 1926 그림 (Graph Traversal)

선주 2023. 2. 12. 17:42

 

📌 풀이

💬 Code

import Foundation

let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
let n = input[0]
let m = input[1]

var graph = [[Int]]()
for _ in 0..<n {
    graph.append(readLine()!.split(separator: " ").map{ Int(String($0))! })
}

let dx = [-1, 1, 0, 0]
let dy = [0, 0, -1, 1]
var pics = [Int]()

for i in 0..<n {
    for j in 0..<m {
        if graph[i][j] == 1 {
            pics.append(bfs(i, j))
        }
    }
}

print(pics.count, pics.max() ?? 0, separator: "\n")

func bfs(_ x: Int, _ y: Int) -> Int {
    var idx = 0
    var queue = [[x, y]]
    
    while idx < queue.count {
        let now = queue[idx]
        graph[now[0]][now[1]] = 2
        
        for i in 0..<4 {
            let nx = now[0] + dx[i]
            let ny = now[1] + dy[i]
            if 0..<n ~= nx && 0..<m ~= ny && graph[nx][ny] == 1 {
                queue.append([nx, ny])
                graph[nx][ny] = 2
            }
        }
        idx += 1
    }
    return idx
}

 

 

 

1926번: 그림

어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로

www.acmicpc.net