All problems

Problem 36

Spiral Matrix

Medium · 20 pts · Array, Matrix, Simulation

Problem

You are given a matrix with R rows and C columns. Print all of its elements in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row and up the left column, then repeat the same pattern on the remaining inner part of the matrix until every element has been printed once. Keep four boundaries (top, bottom, left, right) and shrink them after each side is printed. Take care with matrices that have a single row or column left, so that no element is printed twice.

Input

First line: integers R and C. Next R lines: C space-separated integers each.

Output

Print the R * C elements in spiral order, space-separated.

Constraints

1 <= R, C <= 100; -1000 <= value <= 1000

Example input

3 3
1 2 3
4 5 6
7 8 9

Example output

1 2 3 6 9 8 7 4 5

Explanation

For 1 2 3 / 4 5 6 / 7 8 9: the top row gives 1 2 3, the right column continues with 6 9, the bottom row going left gives 8 7, the left column going up gives 4, and the centre 5 is last. The order is 1 2 3 6 9 8 7 4 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Sort Colors Next: Rotate Matrix