How to rotate square matrix 90 degrees to the left in Swift

1 Answer

0 votes
import Foundation

func printMatrix(_ matrix: [[Int]]) {
    for row in matrix {
        print(row.map { String($0) }.joined(separator: " "))
    }
}

/**
 Rotates a square matrix 90 degrees to the left (counterclockwise).
 Parameter matrix: The square matrix to rotate.
 */
func rotateMatrix90DegreesLeft(_ matrix: inout [[Int]]) {
    let len = matrix.count

    // Validate input: Ensure it's a square matrix
    guard matrix.allSatisfy({ $0.count == len }) else {
        fatalError("Input must be a square matrix.")
    }

    // Perform the rotation in-place
    for layer in 0..<(len / 2) {
        let first = layer
        let last = len - 1 - layer

        for i in first..<last {
            let offset = i - first

            // Save the top element
            let 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
        }
    }
}

var matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

rotateMatrix90DegreesLeft(&matrix)

print("Matrix After 90° Left Rotation:")
printMatrix(matrix)



/*
run:

Matrix After 90° Left Rotation:
3 6 9
2 5 8
1 4 7

*/

 



answered Oct 6, 2025 by avibootz
...