#C1981. Spiral Matrix Traversal

    ID: 45246 Type: Default 1000ms 256MiB

Spiral Matrix Traversal

Spiral Matrix Traversal

You are given a two-dimensional matrix \(A\) with \(n\) rows and \(m\) columns. Your task is to print the elements of this matrix in spiral order.

The spiral order starts at the top-left corner and traverses the matrix in the following order:

  • Traverse the first row from left to right.
  • Traverse the last column from top to bottom.
  • If there is any, traverse the last row from right to left.
  • If there is any, traverse the first column from bottom to top.

This procedure is repeated for the remaining submatrix until all elements have been processed.

For example, given the following matrix:

[ \begin{bmatrix} 1 & 2 & 3 & 4 \ 5 & 6 & 7 & 8 \ 9 & 10 & 11 & 12 \end{bmatrix} ]

The output should be:

1 2 3 4 8 12 11 10 9 5 6 7

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains two integers \(n\) and \(m\) representing the number of rows and columns.
  2. The following \(n\) lines each contain \(m\) integers separated by spaces, representing the rows of the matrix.

If \(n = 0\) or \(m = 0\), the matrix is empty and nothing should be printed.

outputFormat

Print to standard output (stdout) a single line containing the elements of the matrix in spiral order, separated by a single space. There should be no trailing spaces.

## sample
3 4
1 2 3 4
5 6 7 8
9 10 11 12
1 2 3 4 8 12 11 10 9 5 6 7