Show problems as
Classic problem #59MediumArrayMatrixSimulation

Spiral Matrix II

Real-world version: Stamping the Courtyard Slabs
Tracked in this browser only
Read Spiral Matrix II on LeetCode(opens in a new tab)

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

A paving crew is laying a square courtyard of side rows by side columns of slabs. Every slab gets a stamped number recording the order it was bedded down, starting at 1 and rising by one for each slab.

The crew works inwards in a spiral. Starting at the slab in the north-west corner they bed the whole top row eastwards, then turn and work down the far-east column southwards, then back along the bottom row westwards, then up the west column northwards, stopping just below the row they started on. That closes one ring. They then repeat the same four legs on the ring of still-bare slabs inside it, and carry on until no bare slab is left.

Return the stamped numbers as a grid of side rows, each row read from west to east.

Examples

Example 1

Input
side = 4
Output
[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]

The top row is stamped 1 to 4 west to east, the east column carries on with 5 to 7 going south, the bottom row takes 8 to 10 heading west, and the west column takes 11 and 12 heading north, which closes the outer ring. The four slabs left in the middle are stamped 13 to 16 the same way.

Example 2

Input
side = 2
Output
[[1, 2], [4, 3]]

The top row takes 1 and 2, the east column takes 4's predecessor 3 below the 2, and the bottom row takes 4 under the 1, so the single ring uses every slab.

Example 3

Input
side = 5
Output
[[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]]

The outer ring uses stamps 1 to 16, the next ring in uses 17 to 24, and the one slab at the centre of the courtyard takes stamp 25.

Constraints

  • 1 <= side <= 20

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 lay_slabs(side: int) -> list[list[int]]:
Java
public int[][] laySlabs(int side)