55 lines
935 B
Go
55 lines
935 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
// rotate90Clockwise rotates the given 2D slice 90 degrees clockwise
|
|
func rotate90Clockwise(matrix [][]int) [][]int {
|
|
n := len(matrix)
|
|
if n == 0 {
|
|
return matrix
|
|
}
|
|
m := len(matrix[0])
|
|
|
|
// Create a new 2D slice to hold the rotated matrix
|
|
rotated := make([][]int, m)
|
|
for i := range rotated {
|
|
rotated[i] = make([]int, n)
|
|
}
|
|
|
|
// Perform the rotation
|
|
for i := 0; i < n; i++ {
|
|
for j := 0; j < m; j++ {
|
|
rotated[j][n-i-1] = matrix[i][j]
|
|
}
|
|
}
|
|
|
|
return rotated
|
|
}
|
|
|
|
// printMatrix prints the 2D slice in a readable format
|
|
func printMatrix(matrix [][]int) {
|
|
for _, row := range matrix {
|
|
fmt.Println(row)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
// Example 2D slice
|
|
matrix := [][]int{
|
|
{1, 2, 3},
|
|
{4, 5, 6},
|
|
{7, 8, 9},
|
|
}
|
|
|
|
fmt.Println("Original matrix:")
|
|
printMatrix(matrix)
|
|
|
|
// Rotate the matrix
|
|
rotatedMatrix := rotate90Clockwise(matrix)
|
|
|
|
fmt.Println("Rotated matrix:")
|
|
printMatrix(rotatedMatrix)
|
|
}
|
|
|