1. 程式人生 > >python 生成螺旋矩陣

python 生成螺旋矩陣

矩陣 mat nbsp num 螺旋矩陣 pos global pre ==

對於任意 m*n 矩陣,將 1~m*n 的數字按照螺旋規則在矩陣中排列。

如 m=3,n=3,期望結果為:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

以下代碼支持方陣以及非方陣。

code:

# coding=utf-8
import numpy

flag=1
pos_x=0
pos_y=0
def inc(pos_x,pos_y,row,col):
    if(-1<pos_x<row and -1<pos_y<col):
        return True
    else
: return False def gen(row,col): global flag global pos_x global pos_y rowbox=[] for i in range(col): rowbox.append(0) data=[] for i in range(row): data.append(rowbox) x = numpy.array(data) for i in range(1,row*col+1):
while(1): if(flag==1): if(inc(pos_x,pos_y,row,col) and x[pos_x][pos_y]==0): x[pos_x][pos_y]=i pos_y=pos_y+1 break else: pos_y=pos_y-1 pos_x=pos_x+1 flag
=2 if(flag==2): if(inc(pos_x,pos_y,row,col) and x[pos_x][pos_y]==0): x[pos_x][pos_y]=i pos_x=pos_x+1 break else: pos_x=pos_x-1 pos_y=pos_y-1 flag=3 if(flag==3): if(inc(pos_x,pos_y,row,col) and x[pos_x][pos_y]==0): x[pos_x][pos_y]=i pos_y=pos_y-1 break else: pos_y=pos_y+1 pos_x=pos_x-1 flag=4 if(flag==4): if(inc(pos_x,pos_y,row,col) and x[pos_x][pos_y]==0): x[pos_x][pos_y]=i pos_x=pos_x-1 break else: pos_y=pos_y+1 pos_x=pos_x+1 flag=1 return x # m*n Matrix m=3 n=6 print(gen(m,n))

輸出

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

python 生成螺旋矩陣