Let there is given a 2D Array of size M x N.we have to print it in spiral form.to get better understand we can go through the given below example.
Example:
import java.util.Scanner;
class SpiralMatrix {
static void
spiralOrder(int Row, int Col, int[][] matrix) {
if
(matrix.length == 0)
return;
int top
= 0;
int down
= Row - 1;// to get
total number of row
int left
= 0;
int right
= Col - 1;// to get
total number of column
System.out.print("Spiral matrix ::");
while
(true) {
// Print top row
for
(int j = left; j <= right; ++j)
System.out.print(matrix[top][j]
+ " ");
top++;
if
(top > down || left > right)
break;
// Print the rightmost column
for
(int i = top; i <= down; ++i)
System.out.print(matrix[i][right]
+ " ");
right--;
if
(top > down || left > right)
break;
// Print the bottom row
for
(int j = right; j >= left; --j)
System.out.print(matrix[down][j]
+ " ");
down--;
if
(top > down || left > right)
break;
// Print the leftmost column
for
(int i = down; i >= top; --i)
System.out.print(matrix[i][left]
+ " ");
left++;
if
(top > down || left > right)
break;
}
System.out.println();
}
public static void
main(String[] args) {
System.out.println("Enter the size of matrix");
String[] R_C
= new Scanner(System.in).nextLine().split(" ");
int row
= Integer.parseInt(R_C[0]);
int col
= Integer.parseInt(R_C[1]);
int arr[][]
= new int[row][col];
for
(int i = 0; i < row; i++) {
System.out.println("Enter number for row [" + (i + 1) + "]
:");
String num[]
= new Scanner(System.in).nextLine().split(" ");
for
(int j = 0; j < col; j++) {
arr[i][j]
= Integer.parseInt(num[j]);
}
}
spiralOrder(row,
col, arr);
}
}
Output :