Question
Matrix Spiral

You are given a 2D matrix with KaTeX can only parse string typed expression rows and KaTeX can only parse string typed expression columns. Your task is to print all the elements of the matrix in spiral order.

Spiral order means starting from the top-left corner of the matrix, you first traverse the top row from left to right, then move down along the last column, then traverse the bottom row from right to left, and finally move up along the first column. After completing one outer layer, you continue the same process for the inner remaining matrix until all elements are visited.

In simpler terms, you move around the matrix layer by layer in a spiral pattern.

Input
The first line contains two integers KaTeX can only parse string typed expression and KaTeX can only parse string typed expression — the number of rows and columns in the matrix.

The next KaTeX can only parse string typed expression lines each contain KaTeX can only parse string typed expression integers representing the matrix elements —
KaTeX can only parse string typed expression.
Output
Print a single line containing KaTeX can only parse string typed expression integers — the elements of the matrix in spiral order.
Example
Input
3 3
1 2 3
4 5 6
7 8 9

Output
1 2 3 6 9 8 7 4 5

Explanation

The spiral traversal follows these steps:

Traverse the top row → 1 2 3
Traverse the right column → 6 9
Traverse the bottom row (reverse) → 8 7
Traverse the left column (upwards) → 4
Move to the inner layer → 5

Final spiral order: 1 2 3 6 9 8 7 4 5

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

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

Explanation

We move layer by layer around the matrix:

Top row → 1 2 3 4
Right column → 8 12
Bottom row (reverse) → 11 10 9
Left column (upwards) → 5
Inner layer → 6 7

Final spiral order: 1 2 3 4 8 12 11 10 9 5 6 7

Online