How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in Swift

1 Answer

0 votes
import Foundation

func generateSpiralMatrix(n: Int) -> [[Int]] {
    // Initialize n x n matrix with zeros
    var matrix = Array(repeating: Array(repeating: 0, count: n), count: n)
    
    // Boundary variables
    var top = 0
    var bottom = n - 1
    var left = 0
    var right = n - 1
    
    var num = 1
    
    while top <= bottom && left <= right {
        // Fill top row from left to right
        for col in left...right {
            matrix[top][col] = num
            num += 1
        }
        top += 1
        
        // Fill right column from top to bottom
        for row in top...bottom {
            matrix[row][right] = num
            num += 1
        }
        right -= 1
        
        // Fill bottom row from right to left (if there are remaining rows)
        if top <= bottom && left <= right {
            for col in stride(from: right, through: left, by: -1) {
                matrix[bottom][col] = num
                num += 1
            }
            bottom -= 1
        }
        
        // Fill left column from bottom to top (if there are remaining columns)
        if left <= right && top <= bottom {
            for row in stride(from: bottom, through: top, by: -1) {
                matrix[row][left] = num
                num += 1
            }
            left += 1
        }
    }
    
    return matrix
}

func printMatrix(_ matrix: [[Int]]) {
    let n = matrix.count
    let maxWidth = String(n * n).count
    
    for row in matrix {
        let formattedRow = row.map { String(format: "%\(maxWidth)d", $0) }.joined(separator: " ")
        print(formattedRow)
    }
}

let n = 4
let spiralMatrix = generateSpiralMatrix(n: n)

print("Spiral Matrix (\(n)x\(n)):")
printMatrix(spiralMatrix)



/*
run:

Spiral Matrix (4x4):
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7

*/

 



answered Jun 25 by avibootz
...