Java Question Data structure 04

Given a two-dimensional array, write a program to print it out in spiral order, 

Ex: 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

  
//Q4.java
public class Q4
{
public static void main(String args[])
{
int[][] mat ={ {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16} };
int top = 0, bottom = mat.length - 1 ;
int left = 0, right = mat[0].length - 1 ;

while(true)
{
if(left > right)
{
break;
}
for(int i = left ; i <= right ; i++)
{
System.out.print(mat[top][i] + " ");
}
top++;
if(top > bottom)
{
break;
}
for(int i = top; i <= bottom ; i++)
{
System.out.print(mat[i][right] + " ");
}
right--;
if(left > right)
{
break;
}
for(int i = right ; i >= left; i--)
{
System.out.print(mat[bottom][i]+" ");
}
bottom--;
if(top > bottom)
{
break;
}
for(int i = bottom; i >= top; i--)
{
System.out.print(mat[i][left]+ " ");
}
left++;

}
}


}





 
download code 

Comments