#C7046. Spiral Order Traversal of a Matrix

    ID: 50874 Type: Default 1000ms 256MiB

Spiral Order Traversal of a Matrix

Spiral Order Traversal of a Matrix

You are given a square matrix \(B\) of size \(N \times N\). Your task is to output the elements of the matrix in a spiral order, starting from the top-left element and moving to the right, then downwards, leftwards and upwards, layer by layer.

Spiral Order Explanation:
If you denote the indices of the matrix as \(B_{i,j}\) (with \(i,j = 0,1,\dots,N-1\)), then you are required to traverse the matrix in the following order:
\[ \begin{array}{cccc} B_{0,0} & B_{0,1} & \cdots & B_{0,N-1} \\ B_{1,0} & & & B_{1,N-1} \\ \vdots & & & \vdots \\ B_{N-1,0} & B_{N-1,1} & \cdots & B_{N-1,N-1} \end{array} \] The spiral order is obtained by repeatedly traversing the outer border of the remaining elements and moving inward.

Example 1:
Input:
3 1 2 3 4 5 6 7 8 9
Output:
1 2 3 6 9 8 7 4 5

Example 2:
Input:
4 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

inputFormat

The first line of input contains a single integer \(N\), the size of the matrix.

The next \(N\) lines contain \(N\) space-separated integers each, representing the matrix \(B\).

Note: If \(N = 0\), the matrix is empty.

outputFormat

Output a single line containing the elements of the matrix in spiral order, separated by a space.

## sample
3
1 2 3
4 5 6
7 8 9
1 2 3 6 9 8 7 4 5