How to print a given matrix in spiral form with Kotlin

1 Answer

0 votes
fun printMatrixInSpiralForm(matrix: List<List<Int>>) {
    if (matrix.isEmpty()) return

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

    while (true) {
        if (left > right) break

        // Top row
        for (i in left..right) {
            print("${matrix[top][i]} ")
        }
        println()
        top++

        if (top > bottom) break

        // Right column
        for (i in top..bottom) {
            print("${matrix[i][right]} ")
        }
        println()
        right--

        if (left > right) break

        // Bottom row
        for (i in right downTo left) {
            print("${matrix[bottom][i]} ")
        }
        println()
        bottom--

        if (top > bottom) break

        // Left column
        for (i in bottom downTo top) {
            print("${matrix[i][left]} ")
        }
        println()
        left++
    }
}

fun main() {
    val matrix = listOf(
        listOf(1, 2, 3, 4),
        listOf(5, 6, 7, 8),
        listOf(9, 10, 11, 12),
        listOf(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 by avibootz
...