https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
import Foundation
func solution() {
let N = Int(readLine()!)!
var block = 0
var result: [Int] = []
var visited: [[Bool]] = Array(repeating: Array(repeating: false, count: N), count: N)
var apartmentBoard: [[Int]] = []
for _ in 1...N {
let inputs = readLine()!
.compactMap { Int(String($0)) }
apartmentBoard.append(inputs)
}
for i in 0..<N {
for j in 0..<N {
if apartmentBoard[i][j] == 0 {
visited[i][j] = true
continue
}
if visited[i][j] { continue }
bfs(i, j)
}
}
func bfs(_ i: Int, _ j: Int) {
let dx = [1, -1, 0, 0]
let dy = [0, 0, 1, -1]
var index = 0
var queue: [(Int, Int)] = []
queue.append((i, j))
visited[i][j] = true
while index < queue.count {
let (x, y) = queue[index]
index += 1
for i in 0..<4 {
let nx = x + dx[i]
let ny = y + dy[i]
if nx < 0 || ny < 0 || N <= nx || N <= ny { continue }
if visited[nx][ny] || apartmentBoard[nx][ny] == 0 { continue }
visited[nx][ny] = true
queue.append((nx, ny))
}
}
result.append(index)
block += 1
}
print(block)
result.sorted(by: <)
.forEach { print($0) }
}
solution()
'백준 > 실버' 카테고리의 다른 글
[Swift] 3986번 : 좋은 단어 (0) | 2024.03.18 |
---|---|
[Swift] 4949번 : 균형잡힌 세상 (0) | 2024.03.18 |
[Swift] 2583번 : 영역 구하기 (0) | 2024.03.18 |
[Swift] 7672번 : 나이트의 이동 (0) | 2024.03.18 |
[Swift] 1012번 : 유기농 배추 (0) | 2024.03.18 |