Print two dimensional array in spiral order

Source code:

 package com.in2soft.test;  
 public class PrintSpiralTest {  
  /**  
   * @since Dec 26, 2015  
   * @author Shashwat.Anand  
   */  
  public static void main(String[] args) {  
   int[][] twoDArry = { { 2, 4, 6, 8 }, { 5, 9, 12, 16 }, { 2, 11, 5, 9 }, { 3, 2, 1, 8 } };  
   printInSpiralOrder(twoDArry, twoDArry[0].length, twoDArry.length);  
  }  
  private static void printInSpiralOrder(int[][] twoDArry, int m, int n) {  
   int t = 0, b = m - 1, l = 0, r = n - 1;  
   int dir = 0; // 0 = -> ; 0 = bottom; 0 = <-; 0 = top  
   while (t <= b && l <= r) {  
    if (dir == 0) {  
     for (int i = l; i <= r; i++) {  
      System.out.println(twoDArry[t][i]);  
     }  
     t++;  
     dir = 1;  
    } else if (dir == 1) {  
     for (int i = t; i <= b; i++) {  
      System.out.println(twoDArry[i][r]);  
     }  
     r--;  
     dir = 2;  
    } else if (dir == 2) {  
     for (int i = r; i >= l; i--) {  
      System.out.println(twoDArry[b][i]);  
     }  
     b--;  
     dir = 3;  
    } else if (dir == 3) {  
     for (int i = b; i >= t; i--) {  
      System.out.println(twoDArry[i][l]);  
     }  
     l++;  
     dir = 0;  
    }  
   }  
  }  
 }  

Comments

Popular posts from this blog

Comparison of Cloud Services

When to use Import-Package and Require-Bundle in Eclipse Plugin?