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]);
}
}
}
here is some Java solution: