N = 3 matrix = [[0] * N for _ in range(N)] num = 16 row, col = 0, 0 direction = 1 for i in range(N*N): matrix[row][col] = num num -= 1 if direction == 1: if row < N-1 and matrix[row+1][col] == 0: row += 1 else: direction = 2 col += 1 elif direction == 2: if col < N-1 and matrix[row][col+1] == 0: col += 1 else: direction = 3 row -= 1 elif direction == 3: if row > 0 and matrix[row-1][col] == 0: row -= 1 else: direction = 4 col -= 1 else: if col > 0 and matrix[row][col-1] == 0: col -= 1 else: direction = 1 row += 1 for row in matrix: print(row)
matrix = [[0] * N for _ in range(N)]
num = 16
row, col = 0, 0
direction = 1
for i in range(N*N):
matrix[row][col] = num
num -= 1
if direction == 1:
if row < N-1 and matrix[row+1][col] == 0:
row += 1
else:
direction = 2
col += 1
elif direction == 2:
if col < N-1 and matrix[row][col+1] == 0:
col += 1
else:
direction = 3
row -= 1
elif direction == 3:
if row > 0 and matrix[row-1][col] == 0:
row -= 1
else:
direction = 4
col -= 1
else:
if col > 0 and matrix[row][col-1] == 0:
col -= 1
else:
direction = 1
row += 1
for row in matrix:
print(row)
Результат:
[16, 9, 8][15, 10, 7]
[14, 11, 6]