Monday 30 January 2017

spiral matrix






Outer spiral matrix– arrows are from boundary to core element. Inner Spiral matrix– Arrows are from core elements to boundary elements.


import java.util.*;     //for importing scanner class
class spiral
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);   //can also be done by BufferReader. But then use: import.java.io.*;
System.out.print("\nEnter the size of matrix (nxn):");
int n=obj.nextInt();
int a[][]=new int[n][n];
System.out.println("Your matrix is of order "+n+"x"+n+"\n");
int d,c,i,j,l,t,m,k;
d=n-1;
c=n*n+1;     // if its 3x3 matrix then 1-9 elements are filled. So c=10. afterwards --c making 9,8,.....1
for(i=;i<=(n+1)/2;i++)
{
for(j=i;j<=d;j++)   //first from west to east
a[i][j]=--c;
for(l=i+1;l<=d;l++)   //    north to south
a[l][d]=--c;
for(k=d-1;k>=i;k--)      //east to west
a[d][k]=--c;
for(m=d-1;m>i;m--)   //south to north
a[m][i]=--c;
d--;               // reducing the size of spiral
}
for(i=;i<n;i++)
{
for(j=;j<n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}










No comments:

Post a Comment

Goldbach Number ISC 2018

Question: A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes. Note: All even integer numbers ...