</>CodexBash
Back to problems
Not started

Read the grid in a spiral

Medium
2000 ms limit256 MB memoryArraysMatrices

Stuck?

Show a hint

Hold four boundaries and move each one inward after walking its edge. Guard the bottom and left walks, or a single remaining row is read twice.

The idea behind this problem

Last problem in this lesson

Go to the next lesson

Return all the values of a grid in spiral order: left along the top, down the right side, back along the bottom, up the left side, then inward and repeat.

Worked example#

For

1 2 3
4 5 6
7 8 9

the path is 1 2 3 across the top, 6 9 down the right, 8 7 back along the bottom, 4 up the left, and finally 5 in the middle.

The answer is 1 2 3 6 9 8 7 4 5.

Four walls closing in#

The clean way to write this is to hold four boundaries: top, bottom, left and right. Walk one edge, then move that boundary inward, and stop when the boundaries cross.

stepdirectionboundary that moves
across the topleft to righttop moves down
down the righttop to bottomright moves left
back along the bottomright to leftbottom moves up
up the leftbottom to topleft moves right

The case that catches everyone#

After the first two edges the remaining shape may be a single row or a single column. If you walk the bottom edge without checking top <= bottom first, you walk a row you have already read and emit its values twice.

So the last two of the four moves each need a guard:

if top <= bottom:  walk the bottom edge
if left <= right:  walk the left edge

The first two do not, because the loop condition has just checked them. A grid that is one row tall, or one column wide, is the shortest way to see this fail.

The cost#

Time O(rows x cols), since every cell is emitted exactly once. Memory O(1) beyond the answer itself.

Constraints#

  • 1 <= rows, cols <= 100
  • The grid need not be square
  • -1000 <= value <= 1000

Input

matrix is a row count, then a column count, then the values row by row.

Output

The values in spiral order, separated by spaces.

Examples

Input

3 3
1 2 3
4 5 6
7 8 9

Output

1 2 3 6 9 8 7 4 5

Across the top, down the right, back along the bottom, up the left, then the middle.

Input

1 4
1 2 3 4

Output

1 2 3 4

A single row: the guard is what stops it being read back again.

Input

3 1
1
2
3

Output

1 2 3

A single column, for the same reason.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.