Tuesday, December 24, 2013

Java 2D-Array Spiral Order Traversal Implementation

Recently, I came across a problem that required iterating through the elements of the 2D array in a clockwise inward spiral starting from the top left cell of the matrix. Basically we have a 2d array, and the requirement is to represent it with a 1D array printing the elements in a spiral order (as in example below).


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




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


Am sure there is a much better and efficient way to solve this problem. Here is my version of the implementation (recursion approach) that works for any n*n matrix. Details in the self-explanatory Java code: