Home » Posts » How to print a matrix in spiral form?

How to print a matrix in spiral form?

This is a very common question asked in many programming competitions and interviews. The problem statement says that, “given a matrix, we need to print it’s content in spiral pattern”. For example, if we have a matrix like below then the output would be 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12.

Algorithm

Below are the steps to solve this problem.

  1. Initialize four variables
    1. Top row – Pointing to the first row of the matrix.
    2. Bottom row – Pointing to the last row of the matrix.
    3. Left column – Pointing to the first column of the matrix.
    4. Right column – Pointing to the last column of the matrix.
  2. Loop until top row is before bottom row and left column is before right column
    1. Print the row pointed by top row from left column to right column (left to right).
    2. Move top row to the next row in the matrix.
    3. Print the right column from top row to bottom row (top to bottom).
    4. Move right column to its previous column in the matrix.
    5. Print bottom row from right column to left column (right to left).
    6. Move bottom row to its previous row in the matrix.
    7. Print left column from bottom row to top row (bottom to top).
    8. Move left column to its next column in the matrix.

Implementation

Below is code example in Java showing the implementation of the above algorithm.

package com.theaconitedev;

public class Main {

    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4, 5},
                {6, 7, 8, 9, 10},
                {11, 12, 13, 14, 15},
                {16, 17, 18, 19, 20}
        };
        spiralPrint(matrix);
    }

    public static void spiralPrint(int[][] matrix) {
        int leftColumn = 0;
        int rightColumn = matrix[0].length - 1;
        int topRow = 0;
        int bottomRow = matrix.length - 1;

        while ((topRow <= bottomRow) && (leftColumn <= rightColumn)) {
            for (int i = leftColumn; i <= rightColumn; i++) {
                System.out.print(matrix[topRow][i] + " ");
            }

            topRow++;

            for (int i = topRow; i <= bottomRow; i++) {
                System.out.print(matrix[i][rightColumn] + " ");
            }

            rightColumn--;

            for (int i = rightColumn; i >= leftColumn; i--) {
                System.out.print(matrix[bottomRow][i] + " ");
            }

            bottomRow--;

            for (int i = bottomRow; i >= topRow; i--) {
                System.out.print(matrix[i][leftColumn] + " ");
            }

            leftColumn++;
        }
    }
}