To rotate a matrix by 90 degrees, we need to swap the elements in the matrix in a specific pattern. Here’s a step-by-step algorithm to rotate a matrix by 90 degrees clockwise:
- Transpose the matrix: swap the elements in the matrix along its main diagonal.
- Reverse each row: for each row in the transposed matrix, reverse the order of its elements.
This will give us the matrix rotated by 90 degrees clockwise.
Here’s an example Kotlin code to implement this algorithm:
fun rotateMatrix(matrix: Array<IntArray>) {
val n = matrix.size
// Transpose the matrix
for (i in 0 until n) {
for (j in i until n) {
val temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}
// Reverse each row
for (i in 0 until n) {
for (j in 0 until n / 2) {
val temp = matrix[i][j]
matrix[i][j] = matrix[i][n - j - 1]
matrix[i][n - j - 1] = temp
}
}
}
fun main() {
val matrix = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6),
intArrayOf(7, 8, 9)
)
println("Original matrix:")
printMatrix(matrix)
rotateMatrix(matrix)
println("Rotated matrix:")
printMatrix(matrix)
}
fun printMatrix(matrix: Array<IntArray>) {
for (row in matrix) {
for (cell in row) {
print("$cell ")
}
println()
}
}
In this code, the rotateMatrix
function takes a 2D array of integers matrix
as input and rotates the matrix by 90 degrees clockwise. The function first transposes the matrix by swapping the elements along its main diagonal, and then reverses each row of the transposed matrix. The resulting matrix is the rotated matrix.
Note that this code assumes that the input matrix is a square matrix, but you can modify the code to handle rectangular matrices as well.
we create a square 2D array matrix
and initialize it with some values. We then print the original matrix to the console using the printMatrix
function. Next, we call the rotateMatrix
function to rotate the matrix by 90 degrees clockwise. Finally, we print the rotated matrix to the console using the printMatrix
function.
Output :
Original matrix:
1 2 3
4 5 6
7 8 9
Rotated matrix:
7 4 1
8 5 2
9 6 3