分类:蛇形矩阵
知识点:
取出每行中非零的数字 row = [str(num) for num in matrix[i] if num != 0]
题目来自【牛客】
- def generate_snake_matrix(n):
- # 初始化一个N×N的矩阵
- matrix = [[0] * n for _ in range(n)]
- start = 1
- # i为行,(0~n-1)
- for i in range(n):
- # j为列,(0~i)
- for j in range(i + 1):
- # 将数字依次填入矩阵
- matrix[i - j][j] = start
- start += 1
-
- result = []
- for i in range(n):
- # 取出每行中非零的数字并转换为字符串
- row = [str(num) for num in matrix[i] if num != 0]
- # 以空格连接每行中的数字
- result.append(' '.join(row))
- return result
-
- # 输入
- N = int(input())
-
- # 生成蛇形矩阵并输出结果
- snake_matrix = generate_snake_matrix(N)
- for row in snake_matrix:
- print(row)
-