Skip to content
UniCircle
MediumCodingMatrix

Spiral tour of a seating grid

Question DSA-MAT-111

An exam hall has seats in r rows and c columns, each with a roll number. The invigilator walks in a clockwise spiral: along the top row, down the right column, back along the bottom row, up the left column, and so on inwards.

Print the roll numbers in the order she passes them.

Constraints

  • 1 ≤ r, c ≤ 200

Input and output

Input
Line 1: r and c. Then r lines with c integers each.
Output
All r·c numbers on one line, in spiral order, separated by spaces.

Examples

Input 1

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

Right along the top, down the right edge, back along the bottom, up, then the middle.

Input 2

1 3
7 8 9

Output

7 8 9

A single row is read left to right.

Show hints
  • Keep four boundaries: top, bottom, left, right.
  • After walking one edge, move that boundary inwards and stop when they cross.
Show the explanation

Maintain top, bottom, left and right. Walk the top row left→right and move top down; walk the right column top→bottom and move right left; then, only if rows remain, walk the bottom row right→left and move bottom up; and only if columns remain, walk the left column upwards and move left right. The two checks stop a single remaining row or column from being printed twice.

Original UniCircle question. Last reviewed 22 Oct 2026.