Search code examples
javaarraysspiral

print 2-D array in spiral order


Possible Duplicate:
Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)

How to print a 2 dimensional array in spiral order using JAVA? Please help, I don't have any idea.

sample array:

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

here is what i tried:

public static void main(String[] args) {

    int[][] values = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};

    for (int i = (values.length * values[0].length)-1, j = 0; i > 0; i--, j++) {
          for (int k = j; k < i; k++) {
              System.out.print(values[j][k]);
          }

          for (int k = j; k < i; k++) {
              System.out.print(values[k][i]);
          }

          for (int k = i; k > j; k--) {
              System.out.print(values[i][k]);
          }

          for (int k = i; k > j; k--) {
              System.out.print(values[k][j]);
          }
    }

}

Solution

  • here is some Java solution:

    public static final int X_SIZE = 4;
    public static final int Y_SIZE = 4;
    
    public static void main(String[] args) {
        int[][] array = new int[X_SIZE][Y_SIZE];
    
        for(int i = 0; i < X_SIZE; i++){
            for (int j = 0; j < Y_SIZE; j++){
                array[i][j] = i * X_SIZE + (j + 1);
                System.out.print(array[i][j] + " ");
            } 
            System.out.println();
        }
    
        System.out.println("************");
        System.out.println("Spiral");       
    
        spiralPrint(X_SIZE, Y_SIZE, array);
    }
    
    public static void spiralPrint(int xSize, int ySize, int matrix[][]){
        int i,  k = 0, l = 0;
        xSize--;  ySize--;      
    
        while(k <= xSize && l <= ySize){
            for(i = l; i <= ySize; ++i) {
                System.out.print(matrix[k][i]+ " ");
            }           
            k++;
    
            for(i = k; i <= xSize; ++i) {
                System.out.print(matrix[i][ySize] + " ");
            }
            ySize--;
    
            for(i = ySize; i >= l; --i) {
                    System.out.print(matrix[xSize][i] + " ");
            }
            xSize--;
    
    
            for(i = xSize; i >= k; --i) {
                System.out.print(matrix[i][l] + " ");
            }
            l++;
        }
    }