Amazon Interview Question
Software Engineer / DevelopersKeep traversing the matrix and when you reach the boundary, change direction and keep proceeding. in addition to changing the direction you also knock off the opposite boundary which you have already traversed, keeping in mind not to do so the first time as you haven't yet traversed it.
void printspiralmatrix(int a[HEIGHT][WIDTH])
{
int n,m;
n=HEIGHT;
m=WIDTH;
int direction = 0; //0 == lt-rt, 1= up to down, 2=rt to left, 3 = down to up
int lh = 0, rh = n-1, up = 0, dn = m-1;
int x=0,y=0;
while ((x>=lh) && (x<=rh) && (y>=up) && (y<=dn))
{
printf("\t%d",a[y][x]);
switch(direction){
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
break;
}
if ((x== rh) && (y==up))
{
direction++;
if (y!=0)
lh++;
}
else if ((x==lh) && (y==dn))
{
direction++;
rh--;
}
else if ((y==up) && (x==lh))
{
direction++;
dn--;
}
else if ((y==dn) && (x==rh))
{
direction++;
up++;
}
direction = direction % 4;
}
}
int main(int argc, char* argv[])
{
int a[HEIGHT][WIDTH]= {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
printspiralmatrix(a);
return 0;
}
public class SpiralSort {
public static void spiralSort(int[][] arr)
{
for(int i=0;i<arr.length;i++)
{
if(i%2==0)
{
System.out.print("{");
for(int j=0;j<arr[0].length;j++)
{
System.out.print(arr[i][j]+", ");
}
System.out.print("}, ");
}
else
{
System.out.print("{");
for(int j=arr[0].length-1;j>-1;j--)
{
System.out.print(arr[i][j]+", ");
}
System.out.print("}, ");
}
}
}
public static void main(String[] args)
{
int arr[][]={{1,2,3},{4,5,6},{7,8,9}};
spiralSort(arr);
}
}
Consider the following code...
- Mayank August 30, 2010