Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,654 questions

51,531 answers

573 users

How to print a given matrix in spiral form with Swift

1 Answer

0 votes
import Foundation

func printMatrixInSpiralForm(_ matrix: [[Int]]) {
    guard !matrix.isEmpty else { return }

    var top = 0
    var bottom = matrix.count - 1
    var left = 0
    var right = matrix[0].count - 1

    while true {
        if left > right { break }

        // Top row
        for i in left...right {
            print("\(matrix[top][i]) ", terminator: "")
        }
        print()
        top += 1

        if top > bottom { break }

        // Right column
        for i in top...bottom {
            print("\(matrix[i][right]) ", terminator: "")
        }
        print()
        right -= 1

        if left > right { break }

        // Bottom row
        for i in stride(from: right, through: left, by: -1) {
            print("\(matrix[bottom][i]) ", terminator: "")
        }
        print()
        bottom -= 1

        if top > bottom { break }

        // Left column
        for i in stride(from: bottom, through: top, by: -1) {
            print("\(matrix[i][left]) ", terminator: "")
        }
        print()
        left += 1
    }
}

let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

printMatrixInSpiralForm(matrix)



/*
run:

1 2 3 4 
8 12 16 
15 14 13 
9 5 
6 7 
11 
10 

*/

 



answered Jun 12, 2025 by avibootz
...