All tasks
Hardarrayssimulation

Spiral Matrix Traversal

Time limit 2 s · Memory 64 MBAcceptance: —Solved by: 0

Statement

The first line contains n and m. Each of the next n lines contains m integers — an n×m matrix. Print the elements in spiral order: starting at the top-left corner and going clockwise — the first row to the right, then the last column down, and so on inward. Print the result on one line separated by spaces.

Examples

Example 1
Input
3 3
1 2 3
4 5 6
7 8 9
Output
1 2 3 6 9 8 7 4 5
Example 2
Input
1 4
1 2 3 4
Output
1 2 3 4

Constraints

  • 1 ≤ n, m ≤ 300
  • -10^9 ≤ element ≤ 10^9
Solve this task to unlock the editorial.

AI tutor

Stuck? Get a nudge — the tutor explains the idea, it never hands you the solution.