下图是一个4阶的螺旋数阵:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
数字从1开始,沿着顺时针方向依次填满整个矩阵。
现在给你矩阵的规模n,请你输出n阶螺旋数阵。
输入包含多组数据,每组数据包含一个正整数n(1≤n≤20)。
对应每组数据,输出相应的螺旋数阵。
每组数据之后输出一个空行作为分隔。
3 4
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
import sys
def generateMatrix(n):
res = [[0 for i in range(n)] for j in range(n)]
count = 1
rowIndex1 = 0
rowIndex2 = n - 1
colIndex1 = n - 1
colIndex2 = 0
rowNum = n
while rowNum >= 1:
for i in range(colIndex2, colIndex1 + 1):
res[rowIndex1][i] = count
count += 1
rowIndex1 += 1
for i in range(rowIndex1, rowIndex2 + 1):
res[i][colIndex1] = count
count += 1
colIndex1 -= 1
for i in range(colIndex1, colIndex2 - 1, -1):
res[rowIndex2][i] = count
count += 1
rowIndex2 -= 1
for i in range(rowIndex2, rowIndex1 - 1, -1):
res[i][colIndex2] = count
count += 1
colIndex2 += 1
rowNum -= 2
return res
for i in sys.stdin.readlines():
matrix = generateMatrix(int(i))
for line in matrix:
print(" ".join(map(str, line)))
print()