Create a program to rotate a matrix by 90 degrees clockwise.
HardProblem Statement
Create a program to rotate a matrix by 90 degrees clockwise.
Sample Input
A hardcoded matrix, e.g., [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Sample Output
7 4 1 8 5 2 9 6 3
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
fun rotateMatrix(matrix: Array<Array<Int>>): Array<Array<Int>> {
val n = matrix.size
val rotated = Array(n) { Array(n) { 0 } }
for (i in 0 until n) {
for (j in 0 until n) {
rotated[j][n - i - 1] = matrix[i][j]
}
}
return rotated
}
fun main() {
val matrix = arrayOf(
arrayOf(1, 2, 3),
arrayOf(4, 5, 6),
arrayOf(7, 8, 9)
)
val rotated = rotateMatrix(matrix)
rotated.forEach { println(it.joinToString(" ")) }
}
Input
A hardcoded matrix, e.g., [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Expected Output
7 4 1 8 5 2 9 6 3