Spiral Matrix - Coder's point

## Saturday, March 16, 2019

`````` import java.util.*;
class Spiral
{
int a[][];
int n;
Spiral(int N)
{
a=new int[N][N];
n=N;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
a[i][j]=1+n*i+j;
}
}
void printNormal()
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
void printSpiral()
{
for(int i=n-1,j=0;i>0;i--,j++)
{
for(int k=j;k<i;k++)
System.out.println(a[j][k]+" ");
for(int k=j;k<i;k++)
System.out.println(a[k][i]+" ");
for(int k=i;k>j;k--)
System.out.println(a[i][k]+" ");
for(int k=i;k>j;k--)
System.out.println(a[k][j]+" ");
}
if(n%2==1)
System.out.println(a[(n-1)/2][(n-1)/2]);
}
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter N to create nxn array");
int n=in.nextInt();
Spiral ob=new Spiral(n);
System.out.println("The given array is :");
ob.printNormal();
System.out.println("The given spiral matrix is :");
ob.printSpiral();
}
}
``````
`OUTPUT:`
```Enter N to create nxn array
3
The given array is :
1 2 3
4 5 6
7 8 9
The given spiral matrix is :
1
2
3
6
9
8
7
4
5
```