Task
Construct a square matrix with a size N × N
containing integers from 1
to N * N
in a spiral order, starting from top-left and in clockwise direction.
Example
For n = 3
, the output should be
spiralNumbers(n) = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
Input/Output
-
[execution time limit]
4 seconds (py3) -
[input] integer n
Matrix size, a positive integer.
Guaranteed constraints:3 ≤ n ≤ 100
. -
[output] array.array.integer
My Solution
def edge(spiralMatrix, n, step):
start = 1
for j in range(step):
start += (n - j * 2 - 1) * 4
for i in range(n - step * 2):
spiralMatrix[step][step + i] = start + i
for i in range(n - step * 2 - 1):
spiralMatrix[step + i][-1 - step] = start + (n - (step * 2) - 1) + i
spiralMatrix[-1 - step][-1 - step - i] = start + (n - 1 - step * 2) * 2 + i
spiralMatrix[-1 - step - i][step] = start + (n - 1 - step * 2) * 3 + i
return
def spiralNumbers(n):
spiralMatrix = [[0] * n for i in range(n)]
for step in range((n + 1) // 2):
edge(spiralMatrix, n, step)
return spiralMatrix