ZigZag数组就是形如下图的,依次沿对角线增加->减小交替变换的数组
0 1 5 6 14 15 27 28
2 4 7 13 16 26 29 42
3 8 12 17 25 30 41 43
9 11 18 24 31 40 44 53
10 19 23 32 39 45 52 54
20 22 33 38 46 51 55 60
21 34 37 47 50 56 59 61
35 36 48 49 57 58 62 63
对于N*N的zigzag数组,可以分两部分输出:左上三角+对角线, 右下三角
1. 对于左上三角+对角线,我们可以按每一条递增的斜线填充,假如填充到第cross条斜线(从0开始计数),每一个待填充的a[i][j],都有i+j = cross。
且j, j的取值范围都是0-cross.
如果cross 是偶数,填充的顺序是从左下,到右上,即列号从0->cross;
如果cross是奇数,填充的顺序是从右上到左下,即行号是从0->cross;
2. 对于右下三角,情况则不同,
对角线是第N-1条斜线,所以对于对角线右下方,与之平行的对角线,我们看做是1, 2, ... , N-1条对角线
且对于每个带填充元素a[i][j]的行列取值 范围也不在是0-cross, 其下限都不能取到0,而依次是1,2,3,。。。,N-1
对于奇数对角线,填充顺序是自下而上,按列遍历,列序从cross到n;
对于偶数对角线,填充顺序是自上而下,按行遍历,行序从cross到n;
代码如下
# -*- coding: UTF-8 -*-
def zigzag(n):
matrix = []
for i in range(n):
matrix.append([0] * n)
count = 0
##填充左上角,第cross个对角线,包括主对角线
for cross in range(n):
if cross % 2 == 0:#偶数对角线,自下而上
for i in range(cross, -1, -1):
matrix[i][cross - i] = count
count += 1
else: #奇数对角线,自上而下
for i in range(0, cross+1):
matrix[i][cross - i] = count
count += 1
##填充右下角,主对角线右下的n-1个对角线
for cross in range(1, n):
if cross % 2 == 0: #偶数对角线,自上而下
for i in range(cross, n):
matrix[i][n - 1 + cross - i] = count
count += 1
else: #奇数对角线,自下而上
for i in range(cross, n):
matrix[n - 1 + cross - i][i] = count
count += 1
return matrix
if __name__ == '__main__':
n = 8
matrix = zigzag(n)
for line in matrix:
print(line)
输出:
[0, 1, 5, 6, 14, 15, 27, 28]
[2, 4, 7, 13, 16, 26, 29, 42]
[3, 8, 12, 17, 25, 30, 41, 43]
[9, 11, 18, 24, 31, 40, 44, 53]
[10, 19, 23, 32, 39, 45, 52, 54]
[20, 22, 33, 38, 46, 51, 55, 60]
[21, 34, 37, 47, 50, 56, 59, 61]
[35, 36, 48, 49, 57, 58, 62, 63]