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.

- Initialize four variables
**Top row**– Pointing to the first row of the matrix.**Bottom row**– Pointing to the last row of the matrix.**Left column**– Pointing to the first column of the matrix.**Right column**– Pointing to the last column of the matrix.

- Loop until top row is before bottom row and left column is before right column
- Print the row pointed by
*top row*from*left column*to*right column*(left to right). - Move
*top row*to the next row in the matrix. - Print the
*right column*from*top row*to*bottom row*(top to bottom). - Move
*right column*to its previous column in the matrix. - Print
*bottom row*from*right column*to*left column*(right to left). - Move
*bottom row*to its previous row in the matrix. - Print
*left column*from*bottom row*to*top row*(bottom to top). - Move
*left column*to its next column in the matrix.

- Print the row pointed by

## 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++;
}
}
}
```