Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/matritsa-spiral-aylanish

Spiral traversal

Medium 1000 ms 128 MB 56%
Share

An integer matrix of size $n \times m$ is given. Print its elements on one line in spiral order: from the top-left corner to the right, then down, left, up, moving one layer inward with every turn (clockwise).

Visiting the matrix cells in a spiral toward the center

Input

The first line contains two positive integers $n$ and $m$. Each of the next $n$ lines contains $m$ integers.

Output

One line with $n * m$ space-separated integers.

Note

$1 \le n, m \le 200$
$-1000 \le a_{i,j} \le 1000$

Examples

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

Sign in to submit a solution

Signing up is free and takes a minute.