Ideas
A helical matrix is a spiral matrix whose number starts with the first line to the right, and the downward becomes larger,
The left is bigger, the upward is bigger, and so the loop goes.
The helical matrices are represented by two-dimensional arrays, coordinates (X,Y), i.e. (x-axis, y-coordinate).
The clockwise spiral direction is-> right, down, left, on, with a numerical value that is x plus 1 lattice (1,0), Y plus 1 lattice (0,1), X minus 1 lattice ( -1,0), y minus 1 lattice (0,-1).
The coordinates start at (0,0) and switch directions when out of range or when obstacles are encountered.
The printing of the spiral matrix first assigns a value to the N*n array, according to the law can be seen, each layer is in accordance with the right-> under the-> left-> on the order to increase, so as long as the first number of each layer can be found, the first number is the first digit of the previous layer +4*n-4, Cycle time n minus 2 per time.
Code
through the above analysis, the idea is very clear, thousand words than a yard:
Import Itertools
def Spiral (n,m):
_status = itertools.cycle ([' Right ', ' down ', ' left ', ' up ']) #用于状态周期性的切换
_ Movemap = {
' right ':(1,0),
' down ':(0,1],
' left ':( -1,0),
' up ':(0,-1),
}
pos2no = Dict.fromkeys ([(X,y) for x in range (n) to Y in range (m)])
_pos = (0,0)
_st = Next (_status) for
I in range ( 1,n*m+1):
_oldpos = _pos
_pos = tuple (Map (Sum,zip (_pos,_movemap[_st))) #根据状态进行移动
if (_pos not in pos2no ) or (Pos2no[_pos]): #当超出范围或遇到障碍时切换方向
_st = Next (_status)
_pos = tuple (Map (Sum,zip (_oldpos,_movemap[_st)))
Pos2no[_oldpos] = i return
pos2no
def display_spiral (n,m):
pos2no = Spiral (n,m) for
i in Range (m):
for J in Range (n):
print pos2no[(j,i)], ' \ t ',
print ' \ n '
print '-' *30
Display_ Spiral (4,4)
display_spiral (5,4)