Thursday 25 August 2011

Given a 2D array, print it in spiral form


/**
*
*/

package com.test.p4;

/**
*
@author Thejas
*
*Print a given matrix in spiral form
Given a 2D array, print it in spiral form. See the following examples.

Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
*/

public class print2DSpiral {

/**
*
@param args
*/

int row=3,column=6;
int rowThreshold = row;//number of rows to traverse to print a fixed column
int columnThreshold = column; //number of columns to traverse to print elements of a fixed row
//int array[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int array[][]={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};
/*
* once right reduce rowthreshold by 1
* once down reduce columnthreshold by 1
* once left reduce rowthreshold by 1
* once up reduce columnthreshold by 1
*/

public void printLeft(int i,int j,int value)
{
for(int k=0;k<columnThreshold;k++)
{
if(value > 0)
{
System.out.print(array[i][j]+" ");
value--;j--;
}
}
rowThreshold--;
if(value>0)
{
printUp(i-1, ++j, value);
}
return;
}
public void printRight(int i,int j,int value)
{
for(int k=0;k<columnThreshold;k++)
{
if(value > 0)
{
System.out.print(array[i][j]+" ");
value--;j++;
}
}
rowThreshold--;
if(value>0)
{
printDown(i+1, --j, value);
}
return;
}
public void printUp(int i,int j,int value)
{
for(int k=0;k<rowThreshold;k++)
{
if(value > 0)
{
System.out.print(array[i][j]+" ");
value--;i--;
}
}
columnThreshold--;
if(value>0)
{
printRight(++i, j+1, value);
}
return;
}
public void printDown(int i,int j,int value)
{
for(int k=0;k<rowThreshold;k++)
{
if(value > 0)
{
System.out.print(array[i][j]+" ");
value--;i++;
}
}
columnThreshold--;
if(value>0)
{
printLeft(--i, j-1, value);
}
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

print2DSpiral printIt = new print2DSpiral();
printIt.printRight(0,0,printIt.row*printIt.column);
return;
}

}

No comments:

Post a Comment