[프로그래머스] 2021 Dev-Matching: 웹 백앤드 개발자(상반기) > 행렬 테두리 회전하기 (77485)(Kotlin)
문제 설명
[입출력 예]
rows | columns | queries | result |
---|---|---|---|
6 |
6 |
[[2,2,5,4],[3,3,6,6],[5,1,6,3]] |
[8, 10, 25] |
3 |
3 |
[[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] |
[1, 1, 5, 3] |
100 |
97 |
[[1,1,100,97]] |
[1] |
문제 풀이1
class Solution {
fun solution(rows: Int, columns: Int, queries: Array<IntArray>): IntArray {
val matrix = Array(rows + 1) { IntArray(columns + 1) }
val ret = IntArray(queries.size)
for (r in 1 .. rows) for (c in 1 .. columns)
matrix[r][c] = (r - 1) * columns + c
for (i in queries.indices) {
if (i == 2) {
println()
}
ret[i] = rotate(queries[i], matrix)
}
return ret
}
fun rotate(query: IntArray, matrix: Array<IntArray>): Int {
val r1 = query[0]
val c1 = query[1]
val r2 = query[2]
val c2 = query[3]
val temp = matrix[r1][c1]
var min = temp
for (i in r1 until r2) {
matrix[i][c1] = matrix[i + 1][c1]
if (min > matrix[i][c1]) min = matrix[i][c1]
}
for (i in c1 until c2) {
matrix[r2][i] = matrix[r2][i + 1]
if (min > matrix[r2][i]) min = matrix[r2][i]
}
for (i in r2 downTo r1 + 1) {
matrix[i][c2] = matrix[i - 1][c2]
if (min > matrix[i][c2]) min = matrix[i][c2]
}
for (i in c2 downTo c1 + 1) {
matrix[r1][i] = matrix[r1][i - 1]
if (min > matrix[r1][i]) min = matrix[r1][i]
}
matrix[r1][c1 + 1] = temp
return min
}
}