Skip to lesson

Spiral order of a seating plan

A medium problem for practising 5.4 Array & String Techniques. Solve it in your own IDE, check it against every test, and open a hint only when you are stuck. 0/1 solved.

1. Spiral order of a seating plan

medium

An exam hall has r rows of c benches, and each bench has one roll number. The invigilator collects answer sheets in a spiral: along the top row from left to right, down the right column, along the bottom row from right to left, up the left column, and then the same again on the inner benches.

Print the roll numbers in the order the sheets are collected.

Input: The first line has two integers r and c. Each of the next r lines has c integers: the roll numbers in that row, from left to right.

Output: One line with r × c integers separated by single spaces: the roll numbers in collection order.

Limits: 1 ≤ r, c ≤ 300 · 1 ≤ roll number ≤ 10^9

Example 1

Input

3 3
1 2 3
4 5 6
7 8 9

Output

1 2 3 6 9 8 7 4 5

The outer ring gives 1 2 3 6 9 8 7 4, and the middle bench 5 comes last.

Example 2

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

After the outer ring, the inner part is one row: 6 7.

Submit to solve