프로그래밍/코딩테스트

[1926번] 그림 / Swift

turu 2021. 6. 20. 01:25

https://www.acmicpc.net/problem/1926

 

1926번: 그림

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

www.acmicpc.net

 


 

import Foundation

let firstLine = readLine()!.split(separator: " ").map{Int(String($0))!}
let row = firstLine[0]
let col = firstLine[1]
var graph = [[Int]]()
for _ in (0..<row) {
    let input = readLine()!.split(separator: " ").map{Int(String($0))!}
    graph.append(input)
}

var numberOfPicture = 0
var maxSize = 0
var visited = [[Bool]](repeating: [Bool](repeating: false, count: col), count: row)

func bfs(_ start: (Int, Int)) {
    // 이미 체크한 그림이면 종료
    guard visited[start.0][start.1] == false,
          graph[start.0][start.1] == 1 else {
        return
    }
    
    numberOfPicture += 1
    let dy = [0, 1, 0, -1]
    let dx = [1, 0, -1, 0]
    var queue = [start]
    var length = 1 // 현재 그림의 길이
    
    visited[start.0][start.1] = true
    while !queue.isEmpty {
        let first = queue.removeFirst()
        for i in (0..<4) {
            let next = (first.0 + dy[i], first.1 + dx[i])
            if next.0 < 0 || next.0 >= row || next.1 < 0 || next.1 >= col {
                continue
            }
            // 벽이 아니면서 아직 방문한 곳이 아닐 때
            if graph[next.0][next.1] != 0 && !visited[next.0][next.1] {
                length += 1
                graph[next.0][next.1] = length
                queue.append(next)
                visited[next.0][next.1] = true
            }
        }
    }
    if length > maxSize {
        maxSize = length
    }
}

for i in (0..<row) {
    for j in (0..<col) {
        bfs((i,j))
    }
}

print(numberOfPicture)
print(maxSize)
반응형