728x90
https://www.acmicpc.net/problem/1080
1080번: 행렬
첫째 줄에 행렬의 크기 N M이 주어진다. N과 M은 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 행렬 A가 주어지고, 그 다음줄부터 N개의 줄에는 행렬 B가 주어진다.
www.acmicpc.net
문제 풀이
1. 주어진 입력의 A 행렬을 matrix 에 B 행렬을 target 에 저장한다.
2. 이중 for 을 이용하여 matrix 행렬을 탐색한다.
3. matrix[i][j] != target[i][j] 인 경우 이면서 i + 2 < N 이고 j + 2 < M 인 경우이면 (i, j) 를 기준으로 3X3 영역의 값들을 (0 -> 1, 1 -> 0) 으로 바꾸고 바꾼 횟수를 count 에 저장한다.
4. matrix 와 target 을 비교하여 서로 같지 않으면 -1을 출력하고 같으면 count 값을 출력한다.
코드
import java.io.*
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val (N, M) = br.readLine().split(" ").map { it.toInt() }
val matrix = Array(N) { IntArray(M) { 0 } }
val target = Array(N) { IntArray(M) { 0 } }
repeat(N) { index ->
matrix[index] = br.readLine().map { it.digitToInt() }.toIntArray()
}
repeat(N) { index ->
target[index] = br.readLine().map { it.digitToInt() }.toIntArray()
}
var result = 0
for (i in 0 until N) {
if (i + 2 >= N) continue
for (j in 0 until M) {
if ((i + 2) < N && (j + 2) < M && matrix[i][j] != target[i][j]) {
// matrix 와 target 이 서로 다르므로 부분 행렬 3X3의 원소들을 업데이트 한다. (0 -> 1, 1 -> 0)
for (k in i..i + 2) {
for (l in j..j + 2) {
matrix[k][l] = Math.abs(matrix[k][l] - 1)
}
}
result++
}
}
}
var matched = true
loop@ for (i in 0 until N) {
for (j in 0 until M) {
if (matrix[i][j] != target[i][j]) {
matched = false
break@loop
}
}
}
if (matched) println(result)
else println(-1)
}
728x90
'알고리즘(w.KOTLIN) > 그리디(Greedy)' 카테고리의 다른 글
[백준][코틀린][1285] 동전 뒤집기 (0) | 2023.05.08 |
---|---|
[백준][코틀린][2138] 전구와 스위치 (0) | 2023.05.02 |
[백준][코틀린][11399] ATM (0) | 2023.04.22 |
[백준][코틀린][1931] 회의실 배정 (0) | 2023.04.21 |
[백준][코틀린][11047] 동전 0 (0) | 2023.04.17 |