用python写一个蛇形矩阵

蛇形矩阵,如:

10 11 12  1
 9 16 13  2
 8 15 14  3
 7  6  5  4

从右上角大回环,其实挺简单,思路想明白了就顺了。

这样的矩阵可以看做二维数组,python对数组的写法很麻烦,用numpy生成就简单多了

myarray = np.zeros((N, N), dtype=np.int16)

有了数组矩阵,接着分析规律,从右上角开始为1,依次向下循环,所以就是行+1,列不变;当行到最下面时,循环变为列-1,行不变,依次后面是行-1,列不变,最后列+1,行不变,完成一圈大循环。

根据这样的规律,再依次在内部进行小循环,直到所有位置的数据都不为0,就算完成。

# 为什么是不为0,因为我在初始化矩阵的时候用的zeros函数,给每一个位置都赋的初值0。


# -*- coding: utf-8 -*-
"""
Created on Mon May 28 13:37:32 2018
@author: JeremyJone
"""
import pprint
import numpy as np

def main():
    N = int(input('请输入数字:'))
    myarray = np.zeros((N, N), dtype=np.int16)
    x, y = 0, N - 1
    res = myarray[x][y] = 1
    while(res < N * N):
        while(x + 1 < N and (not myarray[x + 1][y])):
            res += 1
            x += 1
            myarray[x][y] = res
        while(y - 1 >= 0 and not myarray[x][y - 1]):
            res += 1
            y -= 1
            myarray[x][y] = res
        while(x - 1 >= 0 and not myarray[x - 1][y]):
            res += 1
            x -= 1
            myarray[x][y] = res
        while(y + 1 < N and not myarray[x][y + 1]):
            res += 1
            y += 1
            myarray[x][y] = res

    pprint.pprint(myarray)
    print(myarray)


if __name__ == '__main__':
    main()

pprint和print差不多,略有差别,有兴趣的自己体会吧。

猜你喜欢

转载自blog.csdn.net/jeremyjone/article/details/80490023