Pages

Tuesday, 25 August 2015

Spiral Matrix in Java

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
package core.geeks;

public class SpriralMatrix {
       public static void main(String[] args) {
              int[][] array = {  {0, 1, 2, 3, 4},
                           {5, 6, 7, 8, 9},
                           {10, 11, 12, 13, 14},
                           {15, 16, 17, 18, 19}};
              printSpiral(array);
       }

       private static void printSpiral(int[][] array) {
              int left=0; int right = array[0].length-1;
              int top = 0; int bottom = array.length-1;
              int count = 0;

              while(right>=left && top <= bottom) {
                    
                     if(count==0) {
                           // print top row
                           for(int i = left;i<=right;i++) {
                                  System.out.print(" "+array[top][i]);
                           }
                           top++;
                     } else if(count==1) {
                          
                           // print right most column
                           for(int i = top;i<=bottom;i++) {
                                  System.out.print(" "+array[i][right]);
                           }
                           right--;
                          
                     } else if(count==2) {
                           // print bottom row in reverse order.
                           for(int i = right;i>=left;i--) {
                                  System.out.print(" "+array[bottom][i]);
                           }
                           bottom--;
                     } else if(count==3) {
                           // print right most column
                           for(int i = bottom;i>=top;i--) {
                                  System.out.print(" "+array[i][left]);
                           }
                           left ++;
                     }
                     count = (count+1)%4;
              }
       }
}

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

No comments:

Post a Comment