# 1. Introduction

Printing a matrix in spiral order means traversing and printing the matrix in a manner that starts from the top-left corner, moves to the top-right corner, then proceeds down to the bottom-right corner, then moves left to the bottom-left corner, and finally moves upwards, continuing in this spiral fashion until all elements are printed. This is a common problem in technical interviews and has practical applications in image processing. In this blog post, we will explore a solution to print a matrix in spiral order using Java.

# 2. Program Steps

1. Define four boundary variables – top, bottom, left, and right – to mark the current boundary of the matrix that needs to be printed.

2. Traverse the matrix in the spiral order: from left to right, then top to bottom, then right to left, and finally bottom to top.

3. Adjust the boundaries after each traversal.

4. Repeat steps 2 and 3 until all boundaries are valid.

# 3. Code Program

```
public class SpiralMatrix {
public static void printSpiral(int[][] matrix) {
if (matrix.length == 0) return;
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// Print top row
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;
// Print rightmost column
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;
// Print bottom row if there are more than one row left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}
// Print leftmost column if there are more than one column left
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
printSpiral(matrix);
}
}
```

### Output:

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

# 4. Step By Step Explanation

1. We initiate four boundary variables (top, bottom, left, right) that help us keep track of the current boundary of the matrix yet to be printed.

2. The while loop ensures that we continue printing until all boundaries have been traversed.

3. Inside the loop, we print the matrix in the following order:

– Top row (from *left* to *right*).

– Rightmost column (from *top* to *bottom*).

– Bottom row (from *right* to *left*), but only if there's more than one row left.

– Leftmost column (from *bottom* to *top*), but only if there's more than one column left.

4. After printing each boundary, we adjust the respective boundary variables.

5. This process is repeated until all elements of the matrix are printed in spiral order.