回旋数字矩阵

写一个函数,给定矩阵的长度级数n,返回一个回旋排列的数字矩阵:
例如:

n=2返回:
1 2

3 4

n=3返回:
1 2 3

4 5 6

7 8 9

import numpy


def Matrix():
    N = 4
    M = N
    array = numpy.zeros((N, M), dtype=numpy.int16)

    # 起始点
    x, y = 0, 0
    res = array[x][y] = 1

    while (res < N * M):
        # 改变起始的位置,可以改变旋转,但必须按规律来
        # 上  左-->右
        while (y + 1 < M and not array[x][y + 1]):
            res += 1
            y += 1
            array[x][y] = res
        # 右  上-->下
        while (x + 1 < N and (not array[x + 1][y])):
            res += 1
            x += 1
            array[x][y] = res
        # 下  右--->左
        while (y - 1 >= 0 and not array[x][y - 1]):
            res += 1
            y -= 1
            array[x][y] = res
        # 左   下--->上
        while (x - 1 >= 0 and not array[x - 1][y]):
            res += 1
            x -= 1
            array[x][y] = res

    print(array)


if __name__ == '__main__':
    Matrix()

原文地址:https://www.cnblogs.com/remixnameless/p/13270169.html