All problems

Spiral Matrix II

Medium · matrix

A mosaic is made of n * n square tiles laid out in a grid of n rows and n columns. The tiles are numbered 1, 2, 3, ... up to n * n in the order a snail would crawl over them. The snail starts on the top-left tile and moves right along the top row to its end, then down the right-hand column, then left along the bottom row, then up the left-hand column, and keeps winding inwards in the same way until it has visited every tile once.

Given n, return the grid with each tile showing its number.

Examples

Example 1

Input: n = 3

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

The snail crosses the top row (1, 2, 3), goes down (4, 5), back along the bottom (6, 7), up (8), and ends in the middle on 9.

Example 2

Input: n = 4

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

Example 3

Input: n = 1

Output: [[1]]

Constraints