47 lines
No EOL
1.4 KiB
Kotlin
47 lines
No EOL
1.4 KiB
Kotlin
class Test48 {
|
|
class Solution {
|
|
fun rotate(matrix: Array<IntArray>): Unit {
|
|
for (i in 0..(matrix.size-1)/2){
|
|
matrix[i] = matrix[matrix.size-1-i]
|
|
.also { matrix[matrix.size-1-i] = matrix[i] }
|
|
}
|
|
|
|
for (i in 1..<matrix.size){
|
|
for (j in 0..i){
|
|
matrix[i][j] = matrix[j][i]
|
|
.also { matrix[j][i] = matrix[i][j] }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun test() {
|
|
val solution = Solution()
|
|
|
|
// 测试用例 1
|
|
val matrix1 = arrayOf(
|
|
intArrayOf(1, 2, 3),
|
|
intArrayOf(4, 5, 6),
|
|
intArrayOf(7, 8, 9)
|
|
)
|
|
solution.rotate(matrix1)
|
|
printMatrix(matrix1) // 预期输出: [[7,4,1],[8,5,2],[9,6,3]]
|
|
|
|
// 测试用例 2
|
|
val matrix2 = arrayOf(
|
|
intArrayOf(5, 1, 9, 11),
|
|
intArrayOf(2, 4, 8, 10),
|
|
intArrayOf(13, 3, 6, 7),
|
|
intArrayOf(15, 14, 12, 16)
|
|
)
|
|
solution.rotate(matrix2)
|
|
printMatrix(matrix2) // 预期输出: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
|
|
}
|
|
|
|
// 辅助函数:打印二维矩阵
|
|
fun printMatrix(matrix: Array<IntArray>) {
|
|
matrix.forEach { row ->
|
|
println(row.joinToString(prefix = "[", postfix = "]", separator = ","))
|
|
}
|
|
}
|
|
} |