Wednesday, February 25, 2015

Print 2D matrix in spiral order

Given a 2D array, print it in spiral form.

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 
 
Below is the java implementation 
  
public class PrintMatrixInSpiral {

 private static int [][] matrix = { 
   {1,2,3,4},
   {5,6,7,8},
   {9,10,11,12},
   {13,14,15,16}};
 
 public static void main(String arg[])
 {
  printSpiral(matrix);
 }
 
 public static void printSpiral(int [][]matrix)
 {
  int top = 0;
  int bottom = matrix.length - 1;
  int left = 0;
  int right = matrix[0].length - 1;
  
  int loop = 0;
  
  while ( top < bottom && left < right )
  {
   /* print row horizontally */
   for( loop = top; loop <= right; loop++)
    System.out.println(matrix[top][loop]);
   
   top++;
   
   /* print last column in all rows */
   for( loop = top; loop <= bottom ; loop++ )
    System.out.println(matrix[loop][right]);
   
   right--;
   
   for( loop = right ; loop >= left; loop--)
    System.out.println(matrix[bottom][loop]);
   
   bottom--;
   
   for(loop = bottom; loop >= top; loop --)
    System.out.println(matrix[loop][left]);
   
   left++;
  }
 }
} 
 

No comments:

Post a Comment