Page 593 - Computer science 868 Class 12
P. 593

Program 10    Spiral Matrix
                                 Define a class Spiral to generate a clock wise spiral matrix of size s. The details of the class
                                 are as follows:
                                 Class Name                   :  Spiral
                                 Data Members
                                 a[][]                        :  to store array
                                 s:                           :  to store number
                                 Member Functions

                                  Spiral(int s1)              :  to initialise s=s1
                                 void generate()              :  to generate spiral matrix
                                 void display()               :   to display the array

                   1       import java.util.*;
                   2       class Spiral

                   3       { int a[][],s;
                   4         Spiral(int s1)

                   5         {s=s1;
                   6          a=new int[s][s];

                   7         }
                   8         void generate()

                   9         { int up=0,le=0,dn=s-1,rt=s-1,c=1,i;
                   10          while(c<=s*s)

                   11          { for(i=le;i<=rt;i++) //top row
                   12            { a[up][i]=c++;

                   13              if(c>s*s) break;
                   14            }

                   15             for(i=up+1;i<=dn;i++) //right column
                   16            { a[i][rt]=c++;

                   17              if(c>s*s) break;
                   18            }

                   19             for(i=rt-1;i>=le;i--) // bottom row
                   20            { a[dn][i]=c++;
                   21              if(c>s*s) break;

                   22            }

                   23             for(i=dn-1;i>=up+1;i--) //left column
                   24            { a[i][up]=c++;
                   25              if(c>s*s) break;



                                                                                                                       591
                                                                                                   Internal Assessment  591
   588   589   590   591   592   593   594   595   596   597   598