python螺旋数字矩阵
给出数字个数n,输出1-n (0<n ≤999)和行数m (0<m ≤ 999),从左上角的1开始,按照顺时针螺旋向内写方式,依次写出2,3.….,最终形成一个m行矩阵。
1.每行数字的个数一样多
2.列的数量尽可能少
3.填充数字时优先填充外部
4.数字不够时,使用单个*号占位
def getRes(n, m):
num_size = n
rows = m
cols, _ = divmod(n, m)
cols = cols + 1 if _ else cols
res = [['*'] * cols for _ in range(rows)]
i, j = 0, 0
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
direction_index = 0
for num in range(num_size):
number = num + 1
res[i][j] = str(number)
nxt_i, nxt_j = directions[direction_index][0] + i, directions[direction_index][1] + j
if not (0 <= nxt_i < rows and 0 <= nxt_j < cols and res[nxt_i][nxt_j] == '*'):
direction_index = (direction_index + 1) % 4
i, j = i + directions[direction_index][0], j + directions[direction_index][1]
for values in res:
print('\t'.join(values))
getRes(9, 4)
n=9,m=4
n=17,m=6