L~Ljm 2021-11-28 15:12 采纳率: 0%
浏览 2

倒s型填数,求做法!()

img


就是给出n值,要求输出nxn的方阵,s型排列,从左上开始

  • 写回答

1条回答 默认 最新

  • 陈.py 2021-11-29 15:48
    关注
    
    import numpy as np
    
    n = int(input(""))
    Array = np.array(range(1, n * n + 1)).reshape(n, n)
    row = 0
    line = 0
    count1 = 1  # 计数器1用于计算蛇形矩阵填充的数
    Max = 2 * n - 2
    for total in range(n):
        if total % 2 == 0:
            for row in range(total + 1):
                line = total - row
                Array[row, line] = count1
                count1 = count1 + 1
        else:
            for line in range(total + 1):
                row = total - line
                Array[row, line] = count1
                count1 = count1 + 1
    
    count2 = 1  # 用于画下三角矩阵
    for total in range(n, Max + 1):
        if total % 2 == 0:
            for row in range(count2, n):
                line = total - row
                Array[row, line] = count1
                count1 = count1 + 1
            count2 = count2 + 1
        else:
            for line in range(count2, n):
                row = total - line
                Array[row, line] = count1
                count1 = count1 + 1
            count2 = count2 + 1
    for line in range(n):
        for row in range(n):
            if row + 1 != n:
                if Array[line, row] < 10:
                    print(' ', end='')
                print(Array[line, row], end='  ')
            else:
                if Array[line, row] < 10:
                    print(' ', end='')
                print(Array[line, row])
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月28日