알고리즘/알고리즘 문제풀이
행렬_백준_1012
Downey
2022. 1. 25. 14:34
https://www.acmicpc.net/problem/1012
OOP스럽게 짜 보았다..
정답
더보기
import Foundation
class Baek1012 {
var matrix: [[Int]]
var warm = 0
let rowLimit: Int
let columnLimit: Int
init(row: Int, column: Int) {
matrix = [[Int]].init(repeating: [Int].init(repeating: 0, count: row), count: column)
self.rowLimit = column
self.columnLimit = row
}
func cabbage(_ row: Int, _ column: Int) {
matrix[column][row] = 1
}
func sol() {
for (row,i) in matrix.enumerated() {
for (column, j) in i.enumerated() {
if matrix[row][column] == 1 {
warm += 1
self.matrix[row][column] = 2
search(row: row, column: column)
}
}
}
}
func search(row: Int, column: Int) {
let moves: [[Int]] = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for move in moves {
let nextRow = row + move[0]
let nextColumn = column + move[1]
if nextRow >= rowLimit ||
nextRow < 0 ||
nextColumn >= columnLimit ||
nextColumn < 0 {
continue
}
if matrix[nextRow][nextColumn] == 1 {
self.matrix[nextRow][nextColumn] = 2
search(row: nextRow, column: nextColumn)
}
}
}
}
let testCaseCount = Int(readLine()!)!
for _ in 0..<testCaseCount {
let input = readLine()!.components(separatedBy:" ").map({Int($0)!})
let solution = Baek1012.init(row: input[0], column: input[1])
for _ in 0..<input[2] {
let cabbageInput = readLine()!.components(separatedBy:" ").map({Int($0)!})
solution.cabbage(cabbageInput[0],cabbageInput[1])
}
solution.sol()
print(solution.warm)
}