← 返回题库
初级

蛇形矩阵

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve(n):
    matrix = [[0] * n for _ in range(n)]
    num = 1
    for diag in range(2 * n - 1):
        if diag < n:
            row, col = 0, diag
            while col >= 0:
                matrix[row][col] = num
                num += 1
                row += 1
                col -= 1
        else:
            row, col = diag - n + 1, n - 1
            while row < n:
                matrix[row][col] = num
                num += 1
                row += 1
                col -= 1
    for row in matrix:
        print(' '.join(map(str, row)))

示例

输入
solve(4)
期望输出
1 2 4 7
3 5 8 11
6 9 12 14
10 13 15 16
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码