How to rotate a matrix 90 degrees clockwise in Swift

2 Answers

0 votes
import Foundation

func rotate90Clockwise(matrix: inout [[Int]]) {
    let N = matrix.count

    // Step 1: Transpose the matrix
    for i in 0..<N {
        for j in i..<N {
            let temp = matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = temp
        }
    }

    // Step 2: Reverse each row
    for i in 0..<N {
        matrix[i].reverse()
    }
}

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

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

print("Original Matrix:")
printMatrix(matrix)

rotate90Clockwise(matrix: &matrix)

print("\nRotated Matrix:")
printMatrix(matrix)

 
 
/*
run:
 
Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3
 
*/

 



answered May 30 by avibootz
0 votes
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
 
*/

 



answered May 30 by avibootz
...