n阶螺旋矩阵

"""
[
[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]
]
"""
def main(n):
    result = [[0] * n for _ in range(n)]
    show_num = 1
    start_line = 0
    row = n - 1
    col = n - 1

    def matrix(start_line, show_num, row, col):
        if row == 0:
            if n % 2 != 0:
                result[n // 2][n // 2] = n * n
        else:
            for i in range(start_line, col):
                result[start_line][i] = show_num
                show_num += 1
            for i in range(start_line, row):
                result[i][row] = show_num
                show_num += 1
            for i in range(row, start_line, -1):
                result[row][i] = show_num
                show_num += 1
            for i in range(col, start_line, -1):
                result[i][start_line] = show_num
                show_num += 1

            return matrix(start_line+1, show_num, row-1, col-1)
    matrix(start_line, show_num, row, col)

    return result


if __name__ == '__main__':
    result = main(4)
    for i in result:
        for x in i:
            print(format(x, '3'), end=' ')
        print()


"""
result:
  1   2   3   4 
 12  13  14   5 
 11  16  15   6 
 10   9   8   7 
"""

你可能感兴趣的:(n阶螺旋矩阵)