Spiral Numbers
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
spiral_numbers(n) = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
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
Input/Output
[input] integer n
Matrix size, a positive integer.
Solution
py
def spiral_numbers(n):
matrix = [[0] * n for _ in range(n)]
h_row, h_col, v_row, v_col = 0, 0, 0, 1
for matrix[h_row][h_col] in range(1, n * n + 1):
if matrix[(h_row + v_row) % n][(h_col + v_col) % n]:
v_row, v_col = v_col, -v_row
h_row, h_col = (h_row + v_row), (h_col + v_col)
return matrix
print(spiral_numbers(3))
js
function spiralNumbers(n) {
let result = [];
for (let i = 0; i < n; i++) {
result.push([]);
}
let [x, y, dx, dy] = [0, 0, 1, 0];
for (let i = 1; i <= n * n; i++) {
result[y][x] = i;
if (x + dx >= n || x + dx < 0 || y + dy >= n || y + dy < 0 || result[y + dy][x + dx] !== undefined) {
let temp = dx;
dx = -dy;
dy = temp;
}
x += dx;
y += dy;
}
return result;
}
console.log(spiralNumbers(3));