python 简单实现螺旋矩阵

创建一个大小为m * n的矩阵,
并以螺旋方式遍历它。
在遍历时,我们跟踪变量“ val”以填充下一个值,
我们将“ val”一个接一个地递增,并将其值放入矩阵中。
以下是简单实现:
def spiral_matrix(m,n):
    '''
    :param x: colunm index
    :param y: row index
    '''
    a = [[0 for _ in range(m)] for _ in range(n)]
    val = 1
    x,y = 0,0
    count = m*n
    while val <= count:
        for i in range(x, m):
            a[x][i] = val
            val += 1
        x += 1
        for i in range(y+1, n):
            a[i][m-1] = val
            val += 1
        y += 1

        if x < m:
            for i in range(m-2, x-2, -1):
                a[n-1][i] = val
                val += 1
            m -= 1

        if y < n:
            for i in range(n-2, y-1, -1):
                a[i][y-1] = val
                val += 1
            n -= 1
    for i in a:
        print(*i)

spiral_matrix(6,6)
# 1 2 3 4 5 6
# 20 21 22 23 24 7
# 19 32 33 34 25 8
# 18 31 36 35 26 9
# 17 30 29 28 27 10
# 16 15 14 13 12 11

你可能感兴趣的:(水贴,python)