#K35532. Spiral Order Matrix Traversal

    ID: 25552 Type: Default 1000ms 256MiB

Spiral Order Matrix Traversal

Spiral Order Matrix Traversal

You are given an m x n matrix. Your task is to output all the elements of the matrix in spiral order. The spiral order starts from the top left corner of the matrix and moves right, down, left, and up, repeating these steps until all elements are traversed.

The spiral order for a given matrix \(A\) can be described by the following steps:

  • Traverse the top row from left to right.
  • Traverse the rightmost column from top to bottom.
  • If there are remaining rows, traverse the bottom row from right to left.
  • If there are remaining columns, traverse the leftmost column from bottom to top.

Print the resulting sequence as space-separated integers in one line.

inputFormat

Input is read from the standard input (stdin). The first line contains two integers \(m\) and \(n\) denoting the number of rows and columns of the matrix, respectively. This is followed by \(m\) lines, each containing \(n\) space-separated integers representing the matrix rows.

outputFormat

Output the spiral order traversal of the matrix elements as space-separated integers on a single line to the standard output (stdout).

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