Show problems as
Classic problem #54MediumArrayMatrixSimulation

Spiral Matrix

Real-world version: Clockwise Panel Readout
Tracked in this browser only
Read Spiral Matrix on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A thermal camera keeps a per-pixel calibration offset for every cell of its sensor, stored as a grid panel of m rows and n columns. Offsets may be negative, since a pixel can read cold as well as hot.

The firmware ships these offsets over a serial link on an inward clockwise track. Starting at the top-left cell it sweeps the first row rightwards, drops down the final column, sweeps the last row back to the left, climbs the first column, and then applies the same track to the rectangle still untouched inside. It stops once every cell has gone out on the wire.

Return the offsets in the exact order the firmware ships them.

Examples

Example 1

Input
panel = [[3, -1, 4], [0, 7, -6], [8, 2, 5]]
Output
[3, -1, 4, -6, 5, 2, 8, 0, 7]

The outer ring goes out first, ending at the offset 0 on the left edge, and the lone inner cell 7 is shipped last.

Example 2

Input
panel = [[9, -2, 3, 6], [4, 0, -8, 1], [7, 5, 2, -3]]
Output
[9, -2, 3, 6, 1, -3, 2, 5, 7, 4, 0, -8]

After the outer ring, the leftover rectangle is the single row `[0, -8]`, which is swept rightwards.

Example 3

Input
panel = [[5], [-2], [0], [8]]
Output
[5, -2, 0, 8]

A one-column sensor gives a track that only ever heads downwards.

Constraints

  • m == panel.length
  • n == panel[i].length
  • 1 <= m, n <= 10
  • -100 <= panel[i][j] <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def readout_order(panel: list[list[int]]) -> list[int]:
Java
public List<Integer> readoutOrder(int[][] panel)