Skip to content

Fill a Grid in Spiral Order

Easy#matrix-traversal#direction-turning~15 min

The mission

Problem

Given a number of rows and columns, build a grid of that size filled with the numbers 1 to rows × cols in an inward clockwise spiral: along the top row to the right, down the right column, back along the bottom row, up the left column, and around again until every cell is filled. Return the grid as a list of rows.

Examples

Input:  rows = 3, cols = 3
Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Why:    the spiral ends in the centre cell
Input:  rows = 3, cols = 4
Output: [[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]
Why:    a wide grid ends on a short middle row instead of a single cell
Input:  rows = 1, cols = 1
Output: [[1]]
Why:    edge case, the spiral is a single step

Hints

0 / 3

Target time
O(rows · cols)
Target space
O(rows · cols)

Stuck on the idea rather than the code? Spiral Order covers it.

Python 3Ctrl+Enter runs
Custom test case