Spiral Matrix

Enter the Size of the Spiral Matrix: 4

7 8 9 10
6 1 2 11
5 4 3 12
16 15 15 13
import java.io.*;
public class spiralMatriX
{
public int a=4,b=3,c=2,f=1,i,j,e,t;//Initialization of Direction counters
public void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter the Size of the Spiral Matrix:”);
e=Integer.parseInt(in.readLine());
int m[][]=new int[e][e];
int k,d,mid,l;
l=e;t=e;t=t-1;k=e-1;d=0;
if(e%2==0)
mid=(e/2)-1;
else
mid=(e-1)/2;
e=e*e;
while(d<=mid)
{
if(a%4==0)
filler(k,d,m);
if(b%4==0)
filler(k,k,m);
if(c%4==0)
filler(d,k,m);
if(f%4==0)
{
filler(d,d,m);
k–;
d++;
t=t-2;
}
}
m[mid][mid]=1;
for(i=0;i<l;i++)
{
for(j=0;j<l;j++){
if(m[i][j]<10)
System.out.print(m[i][j]+”  “);
else
System.out.print(m[i][j]+” “);
}
System.out.println();
}
}
void filler(int y,int z,int n[][]) //Function which filles the MAtrix one by one;
{
for(i=0;i<t;i++)
{
if(a%4==0)
{
n[y][z]=e;
e–;
z++;
}
if(b%4==0)
{
n[y][z]=e;
e–;
y–;
}
if(c%4==0)
{
n[y][z]=e;
e–;
z–;
}
if(f%4==0)
{
n[y][z]=e;
e–;
y++;
}
}
a++;b++;c++;f++;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s