对于任意 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]]