package main
import (
"fmt"
)
// printMatrix prints the matrix to the console
func printMatrix(matrix [][]int) {
for _, row := range matrix {
for _, val := range row {
fmt.Printf("%d ", val)
}
fmt.Println()
}
}
// rotateMatrix90DegreesLeft rotates a square matrix 90 degrees to the left (counterclockwise)
// param matrix - The square matrix to rotate
func rotateMatrix90DegreesLeft(matrix [][]int) {
n := len(matrix)
// Validate input: Ensure it's a square matrix
for _, row := range matrix {
if len(row) != n {
panic("Input must be a square matrix.")
}
}
// Perform the rotation in-place
for layer := 0; layer < n/2; layer++ {
first := layer
last := n - 1 - layer
for i := first; i < last; i++ {
offset := i - first
// Save the top element
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
}
}
}
func main() {
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
rotateMatrix90DegreesLeft(matrix)
fmt.Println("Matrix After 90° Left Rotation:")
printMatrix(matrix)
}
/*
run:
Matrix After 90° Left Rotation:
3 6 9
2 5 8
1 4 7
*/