← Back to challenges

Spiral Matrix Printing

PythonHardarraysloopsmathconditions

Instructions

Write a function that accepts an integer n and returns an n * n spiral matrix.

Examples

matrix(2) ➞ [
  [1, 2],
  [4, 3]
]

matrix(3) ➞ [
  [1, 2, 3],
  [8, 9, 4],
  [7, 6, 5]
]

matrix(4) ➞ [
  [1,  2,  3,  4],
  [12, 13, 14, 5],
  [11, 16, 15, 6],
  [10,  9,  8, 7]
]

Notes

In the examples, traverse the matrix in the clock-wise direction to observe the spiral pattern.

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.