# 02/Swift - CTP
[Swift] 백준! 2667번 - 단지번호붙이기
장딴지연
2023. 1. 20. 01:22
반응형
https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
import Foundation
public struct Queue<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func enquque(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
if isEmpty {
return nil
} else {
return array.removeFirst()
}
}
public var front: T? {
return array.first
}
}
let n = Int(readLine()!)!
var list:[[Int]] = []
var visited:[[Bool]] = []
for _ in 1...n {
let l = Array(readLine()!).map{ Int(String($0))! }
list.append(l)
visited.append(Array.init(repeating: false, count: n))
}
let dir = [[0,1],[0,-1],[1,0],[-1,0]]
var queue = Queue<[Int]>()
func bfs(i:Int, j:Int, c:Int) -> Int {
var c = c
visited[i][j] = true
queue.enquque([i,j])
let num = list[i][j]
while !queue.isEmpty {
let q = queue.dequeue()!
for l in dir {
let x = q[0]+l[0]
let y = q[1]+l[1]
let num = list[q[0]][q[1]]
if x >= 0 && x < n && y >= 0 && y < n && !visited[x][y] && list[x][y] == 1 {
c += 1
queue.enquque([x,y])
list[x][y] = num+1
}
}
}
return c
}
var result:[Int] = []
for i in 0..<n {
for j in 0..<n {
if list[i][j] == 1 && !visited[i][j] {
var c = bfs(i: i, j: j, c: 1)
result.append(c)
}
}
}
print(result.count)
result.sorted().map {
print($0)
}
반응형