print 2-D array in spiral order

scoohh picture scoohh · Oct 20, 2011 · Viewed 19.5k times · Source

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]);
          }
    }

}

Answer

Vlad picture Vlad · Oct 20, 2011
void PrintSpiral(int[][] arr, int size)
{
    for (int l = 0; l < size / 2; l++)
    {
        int min = l;
        int max = size - 1 - l;
        for (int i = min; i < max; i++)
            System.out.print("\t" + arr[i][min].ToString());
        for (int j = min; j < max; j++)
            System.out.print("\t" + arr[max][j].ToString());
        for (int i = max; i > min; i--)
            System.out.print("\t" + arr[i][max].ToString());
        for (int j = max; j > min; j--)
            System.out.print("\t" + arr[min][j].ToString());
    }
    // centre is special case: avoiding printing it 4 times.
    if (size % 2 == 1)
        System.out.print("\t" + arr[size / 2][size / 2].ToString());
}

(disclaimer: tried only on C#)