Sunday, February 20, 2011

BlueJ Program on Spiral Matrix


Spiral matrix means where the values are stored in ascending order in a spiral manner like

01 02 03 04
10 11 12 05
09 08 07 06

For a spiral matrix program, the matrix should be square means both rows and columns should be same.

Codes of the spiral matrix program

import java.io.*;
class Spiral
{
int x;
int t,r,c,i,j,n;
int a[][];
boolean checkDigit(int r)
{
if(r< 10)
return true;
else
return false;
}
void show()throws IOException
{
t=1;
r=0;
c=-1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of array:");
n=Integer.parseInt(br.readLine());
x=n;
a=new int[n][n];
while(n >0)
{
for(i=1;i< =n;i++)
{
a[r][++c]=t++;
}
for(i=1;i< =n-1;i++)
{
a[++r][c]=t++;
}
for(i=1;i< =n-1;i++)
{
a[r][--c]=t++;
}
for(i=1;i< =n-2;i++)
{
a[--r][c]=t++;
}
n=n-2;
}
System.out.println("\nMatrics\n");
for(i=0;i< x;i++)
{
 for(j=0;j< x;j++)
 {
  if(checkDigit(a[i][j]))
 System.out.print("0"+a[i][j]+" ");
 else
 System.out.print(a[i][j]+" ");
 }
 System.out.println();
 }
}
public static void main(String args[])throws Exception
{
 Spiral ob=new Spiral();
ob.show();
}
}

 Analysis of this spiral matrix program

In this program of spiral matrix, four loops within a loop body are required. Two loops are engaged to fill values in the rows of the matrix and the other two for filling the values in columns. The first inner loop fills the values in row from left to right. The second inner loop fills values in the matrix from top to bottom. The third inner loop fills values from right to left and the fourth inner loop fills values from bottom to top. The variable value is incremented by 1 every time it is set in the matrix.  As ‘n’ holds the number of rows and columns in the matrix, after each iteration of the outer loop (here the while loop) value of ‘n’ is decremented by 2.

During display of the spiral matrix values, the values are checked whether it is single digit or not using the function ‘boolean checkDigit()’ which is defined in the class. In case of single digit number, 0 is displayed before the value.

3 comments:

Subscribe via email

Enter your email address:

Delivered by FeedBurner