Print matrix in spiral of matrix in kotlin

Kotlin program for Spiral traversal of matrix. Here problem description and other solutions.

// Kotlin program
// Spiral form of 2d array
class SpiralView
{
    fun spiral(data: Array < Array < Int >> , 
                startRow: Int, startCol: Int, 
                endRow: Int, endCol: Int, 
                element1: Int): Unit
    {
        var i: Int = startCol;
        var element: Int = element1;
        // Left to right
        while (i <= endCol && element > 0)
        {
            element -= 1;
            print("  " + data[startRow][i]);
            i += 1;
        }
        i = startRow + 1;
        // Top to down
        while (i <= endRow && element > 0)
        {
            element -= 1;
            print("  " + data[i][endCol]);
            i += 1;
        }
        i = endCol - 1;
        // Bottom right to bottom-left
        while (i >= startCol && element > 0)
        {
            element -= 1;
            print("  " + data[endRow][i]);
            i -= 1;
        }
        i = endRow - 1;
        // Bottom left to top
        while (i > startRow && element > 0)
        {
            element -= 1;
            print("  " + data[i][startRow]);
            i -= 1;
        }
        if (startRow + 1 <= endRow - 1 && element > 0)
        {
            // Recursive call
            this.spiral(data, startRow + 1, 
                        startCol + 1, endRow - 1, 
                        endCol - 1, element);
        }
    }
}
fun main(args: Array < String > ): Unit
{
    val task: SpiralView = SpiralView();
    // 2d matrix
    val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(1, 2, 3, 4, 5, 6), 
      arrayOf(22, 23, 24, 25, 26, 7), 
      arrayOf(21, 36, 37, 38, 27, 8), 
      arrayOf(20, 35, 42, 39, 28, 9), 
      arrayOf(19, 34, 41, 40, 29, 10), 
      arrayOf(18, 33, 32, 31, 30, 11), 
      arrayOf(17, 16, 15, 14, 13, 12)
    );
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    // Get the number of element
    val element: Int = row * col;
    task.spiral(matrix, 0, 0, row - 1, col - 1, element);
}

Output

  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved