Polski

Spiral matrix

Read the elements of a matrix clockwise, from the outside to the centre. A task about keeping boundaries in check rather than about a clever algorithm.

easy · typescript · javascript · python · csharp · java · go · 10 XP

An LED display draws a "snail" animation: it lights LEDs from the top-left corner along the edges, clockwise and closer to the centre with every lap. We need the order of values for any rectangular m × n matrix.

Task

Return all elements of the matrix in spiral order: the first row to the right, the last column down, the last row to the left, the first column up – and so on for the inner "rings". Every element appears exactly once.

Signatures: spiralOrder(matrix) (JS/TS), spiral_order(matrix) (Python), Solution.SpiralOrder (C#, int[][]), Solution.spiralOrder (Java, int[][]), SpiralOrder (Go).

Examples

MatrixResult
[[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]
[[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]
[[1],[2],[3]][1,2,3]
[] or [[]][]

Constraints

  • 0 ≤ m, n ≤ 500, all rows have the same length.

Expected complexity

O(m · n) time, O(1) extra memory besides the result.