本篇文章小编给大家分享一下利用Python实现n*n螺旋矩阵代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
3*3螺旋矩阵:
1 2 3
8 9 4
7 6 5
实现代码:
def spiral(n): matrix = [[0] * n for _ in range(n)] # 顺时针方向(右,下,左,上) dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] x = y = 0 dn = 0 # 方向指针0;向右填充,1:向下填充,2:向上填充,3:向上填充 for i in range(1, n * n + 1): # 从1开始赋值,一直到n*n matrix[x][y] = i temp_x = x + dx[dn] temp_y = y + dy[dn] if 0 <= temp_x < n and 0 <= temp_y < n and matrix[temp_x][temp_y] == 0: x = temp_x y = temp_y else: dn = (dn + 1) % 4 x += dx[dn] y += dy[dn] return matrix if __name__ == '__main__': n = int(input("输入矩阵n值:")) matrix = spiral(n) for i in range(n): print(matrix[i])
运行结果:
附: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