#K3981. Spiral Order Matrix Traversal

    ID: 26503 Type: Default 1000ms 256MiB

Spiral Order Matrix Traversal

Spiral Order Matrix Traversal

You are given a matrix of dimensions (m \times n). Your task is to output the elements of the matrix in spiral order. In spiral order, you start from the top-left corner, move right across the top row, then down the rightmost column, then left along the bottom row, and finally up the leftmost column. This process is repeated for the remaining submatrix until every element has been visited.

For example, given the matrix [ \begin{bmatrix} 1 & 2 & 3 \ 4 & 5 & 6 \ 7 & 8 & 9 \end{bmatrix} ] The spiral order is: 1, 2, 3, 6, 9, 8, 7, 4, 5.

Read the matrix from standard input and output the spiral order as space-separated values on one line.

inputFormat

The input begins with a single line containing two integers (m) and (n), which represent the number of rows and columns of the matrix respectively. If (m > 0), then the next (m) lines each contain (n) space-separated integers representing the elements of the matrix. For an empty matrix, the input will be '0 0'.

outputFormat

Output a single line containing the elements of the matrix in spiral order, separated by a single space. If the matrix is empty, output nothing.## sample

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