8 September 2013

Print Matrix in Spiral Form (Java)


Hi Friends,

Did you even think to print the matrix in spiral form?? Just try it yourself its interesting to create the algorithm for Spiral form.



Square Matrix
Spiral Matrix
1234
5678
9101112
13141516
  to  
1234
1213145
1116156
1098

Let me explain you an algo to accomplish this task.. (In Java)

class Spiral
{
 public static void main(String args[]) 
 { 
  int n = 4; // matrix size 
  
  int a[][] = new int[n][n];
  int c = 1;
  for (int i = n-1, j = 0; i > 0; i--, j++) 
  {
   for (int k = j; k < i; k++)
   {
    a[j][k]=c++;
   }
   for (int k = j; k < i; k++)
   {
    a[k][i]=c++;
   }
   for (int k = i; k > j; k--)
   {
    a[i][k]=c++;
   }
   for (int k = i; k > j; k--)
   {
    a[k][j]=c++;
   }
  } 
  
  //special case for middle element if value of 'n' is odd
  if (n % 2 == 1)
  {
   a[(n-1)/2][(n-1)/2] = c++;
  }
  
  for(int i = 0; i < n; i++)
  {
   for(int j = 0; j < n; j++)
   {
    System.out.print(a[i][j]+"\t");
   }
   System.out.println();
  } 
 }
}

Just copy paste the above code and save as 'Spiral.java' and compile and run it..

Happy Coding..  :)


1 comment:

  1. My Tactics: Print Matrix In Spiral Form (Java) >>>>> Download Now

    >>>>> Download Full

    My Tactics: Print Matrix In Spiral Form (Java) >>>>> Download LINK

    >>>>> Download Now

    My Tactics: Print Matrix In Spiral Form (Java) >>>>> Download Full

    >>>>> Download LINK zY

    ReplyDelete