1. 问题描述
2. 解题思想
Z字形扫描类似于C语言的金字塔输出
先考虑上半部分,然后在考虑下半部分。
3. 完整代码
# -*- ecoding: utf-8 -*-
# @ModuleName: CSP201412-2
# @Function:
# @Author: ZhangMing
# @Time: 2020/10/5 21:13
n = int(input())
lis = []
out = []
for i in range(n):
temp = list(map(int, input().split()))
lis.append(temp)
x = 0
y = 0
for i in range(2 * n - 1):
if i < n:
while x + y == i and x >= 0 and y >= 0:
out.append(lis[x][y])
if i % 2 == 1: # 减 1操作
y -= 1
x = i - y
else: # 减一操作
x -= 1
y = i - x
if x < 0:
x = 0
y -= 1
if y < 0:
y = 0
x -= 1
if i + 1 == n:
if n % 2 == 1:
x += 1
else:
y += 1
else:
if i % 2 == 0:
y += 1
else:
x += 1
else:
while x + y == i and x < n and y < n:
out.append(lis[x][y])
if i % 2 == 1:
y -= 1
x = i - y
else:
x -= 1
y = i - x
if x >= n:
x = n - 1
y += 1
if y >= n:
y = n - 1
x += 1
if i % 2 == 1:
y += 1
else:
x += 1
out = map(str,out)
print(' '.join(out))
- 运行结果
我的代码耗时较长,应该还有改进的地方,欢迎大家指正交流。