object MatrixRotation {
def printMatrix(matrix: Array[Array[Int]]): Unit = {
matrix.foreach(row => println(row.mkString(" ")))
}
/**
* Rotates a square matrix 90 degrees to the left (counterclockwise).
* param matrix - The square matrix to rotate.
*/
def rotateMatrix90DegreesLeft(matrix: Array[Array[Int]]): Unit = {
val len = matrix.length
// Validate input: Ensure it's a square matrix
if (!matrix.forall(_.length == len)) {
throw new IllegalArgumentException("Input must be a square matrix.")
}
// Perform the rotation in-place
for (layer <- 0 until len / 2) {
val first = layer
val last = len - 1 - layer
for (i <- first until last) {
val offset = i - first
// Save the top element
val top = matrix(first)(i)
// Move right to top
matrix(first)(i) = matrix(i)(last)
// Move bottom to right
matrix(i)(last) = matrix(last)(last - offset)
// Move left to bottom
matrix(last)(last - offset) = matrix(last - offset)(first)
// Move top to left
matrix(last - offset)(first) = top
}
}
}
def main(args: Array[String]): Unit = {
val matrix = Array(
Array(1, 2, 3),
Array(4, 5, 6),
Array(7, 8, 9)
)
rotateMatrix90DegreesLeft(matrix)
println("Matrix After 90° Left Rotation:")
printMatrix(matrix)
}
}
/*
run:
Matrix After 90° Left Rotation:
3 6 9
2 5 8
1 4 7
*/