Spiral Order Print I
Traverse an N * N 2D array in spiral order clock-wise starting from the top left corner. Return the list of traversal sequence.
Assumptions
The 2D array is not null and has size of N * N where N >= 0
Examples
{ {1, 2, 3},
{4, 5, 6},
{7, 8, 9} }
the traversal sequence is [1, 2, 3, 6, 9, 8, 7, 4, 5]
Solution: Recursive print layer by layer
Base Case:
One or none entries in the center
Recursive rule:
For each layer, add
.top left to top right - 1
top right to bottom right - 1
bottom right - bottom left - 1
bottom left to top left - 1
public void spiralTrack(int[][] input, List<Integer> result, int offset, int size){
if(size == 0) return;
if (size == 1){
result.add(input[offset][offset]);
return;
}
for (int i = 0; i < size - 1; i++){ //top left to top right - 1
result.add(input[offset][offset + i]);
}
for (int i = 0; i < size - 1; i++){
result.add(input[i + offset][offset + size - 1]); //top right to bottom right -1
}
for ( int i = size - 1; i >= 1; i--){
result.add(input[offset + size - 1][offset + i]); //bottom right to bottom left - 1
}
for (int i = size - 1; i >= 1; i--){ //bottom left to top left - 1
result.add(input[offset + i][offset]);
}
spiralTrack(input, result, offset + 1, size - 2);
}
Last updated
Was this helpful?