# Java Program to print a given matrix in spiral form

Hello Friends, In this tutorial, we will look at how to print a given matrix in spiral form using Java program, a matrix of size m * n is taken (m is the number of rows and n is the number of columns).

## Print the given matrix in spiral form in Java

Let’s look at the following example:

Matrix M =

1 → 2 → 3

. ↓

4 → 5 6

↑ ↓

7 ← 8 ← 9

Spiral Order of this matrix M is 1 2 3 6 9 8 7 4 5 that is shown using arrows.

In the above matrix number of rows are 3 so m=3, similarly n=3 as the number of columns is 3. So, The total number of elements that have to be printed would be equal to m*n. We maintain four variable as first_row, last_row, first_column and last_column, in each iteration we move from first_column to last_column(left to right) in first_row then first_row+1 to last_row(top to bottom) in last_column then last_col-1 to first_col (right to left) in last_row and finally last_row-1 to first_row+1 (bottom to top) in first_column. After each iteration, we update first_row and first_column by incrementing 1 and last_row and last_column by decrementing 1.

Please look at the attached spiral.java for implementation:

import java.util.*; import java.io.*; public class spiral { public static void main(String[] args) { int [][]a = {{1,2,3},{4,5,6},{7,8,9}}; // 1 2 3 // 4 5 6 // 7 8 9 int m = 3; // number of rows int n = 3; // number of columns int first_row=0; int last_row=m-1; int first_column=0; int last_column=n-1; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { System.out.print(a[i][j]+"\t"); } System.out.println(); } System.out.println("The Output of the given matrix in spiral order: "); int count=0; while((first_row<=last_row) && (first_column<=last_column)) { for(int i=first_column;i<=last_column;i++) { if(count<m*n) { count++; System.out.print(a[first_row][i]+" "); } } for(int i=first_row+1;i<=last_row;i++) { if(count<m*n) { count++; System.out.print(a[i][last_column]+" "); } } for(int i=last_column-1;i>=first_column;i--) { if(count<m*n) { count++; System.out.print(a[last_row][i]+" "); } } for(int i=last_row-1;i>first_row;i--) { if(count<m*n) { count++; System.out.print(a[i][first_column]+" "); } } first_row++; first_column++; last_row--; last_column--; } } }

After Compiling it using javac spiral.java and then executing it using java spiral we get our output as:

1 2 3 4 5 6 7 8 9 The output of the given matrix in spiral order: 1 2 3 6 9 8 7 4 5

## Leave a Reply