Skip to main content

Read a Matrix in a Spiral

MediumArraysMatrix203 tests

You get a matrix matrix with r rows and c columns. Read every value once in spiral order, and return the values as one list.

Spiral order means:

  • Start at the top-left cell and go right along the top row.
  • Go down the right column.
  • Go left along the bottom row.
  • Go up the left column.
  • Then do the same for the smaller matrix that is left inside, until no cell is left.

So the direction turns clockwise each time you reach an edge or a cell you have already read.

Note

Do not read any cell twice. Take care when the part that is left is only one row or one column.

Hint: keep four limits: top, bottom, left and right. After you read one side, move that limit one step inward.

Examples

Example 1

Input:
[[5,1,8],[4,9,2],[7,3,6]]
Output:
[5,1,8,2,6,3,7,4,9]

Top row: 5, 1, 8. Right column going down: 2, 6. Bottom row going left: 3, 7. Left column going up: 4. Then the centre: 9.

Example 2

Input:
[[10,20,30,40],[50,60,70,80]]
Output:
[10,20,30,40,80,70,60,50]

Top row: 10, 20, 30, 40. Right column going down: 80. Bottom row going left: 70, 60, 50. No cell is left.

Example 3

Input:
[[3],[-1],[12]]
Output:
[3,-1,12]

There is one column. Read the top cell, then go down the column: 3, -1, 12.

Constraints

  • 1 <= r, c <= 7
  • -99 <= matrix[i][j] <= 99

Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.