#C2406. Spiral Matrix Traversal

    ID: 45719 Type: Default 1000ms 256MiB

Spiral Matrix Traversal

Spiral Matrix Traversal

Given an \(n \times m\) matrix of integers, perform a spiral traversal starting from the top-left corner. In a spiral traversal, you visit the first row from left to right, then the last column from top to bottom, followed by the last row from right to left, and finally the first column from bottom to top. Continue inwards until all elements have been visited.

Example:

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

</p>

Note: All formulas are written in \(LaTeX\) format. For example, the matrix dimension is given as \(n \times m\).

inputFormat

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

  • The first line contains two integers: n (number of rows) and m (number of columns).
  • The next n lines each contain m space-separated integers representing the matrix.

outputFormat

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

## sample
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10