import Foundation
func rotate90Clockwise(matrix: [[Int]]) -> [[Int]] {
let rows = matrix.count
let cols = matrix[0].count
// Create a new rotated matrix
var rotated = Array(repeating: Array(repeating: 0, count: rows), count: cols)
// Map values to rotated positions
for i in 0..<rows {
for j in 0..<cols {
rotated[j][rows - 1 - i] = matrix[i][j]
}
}
return rotated
}
func printMatrix(_ matrix: [[Int]]) {
for row in matrix {
print(row.map { String($0) }.joined(separator: " "))
}
}
let matrix: [[Int]] = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print("Original Matrix:")
printMatrix(matrix)
let rotated = rotate90Clockwise(matrix: matrix)
print("\nRotated Matrix:")
printMatrix(rotated)
/*
run:
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Rotated Matrix:
9 5 1
10 6 2
11 7 3
12 8 4
*/