algorithm - Print a two dimensional array in an outward spiral -
i asked question in interview:
given (n x m)array, say:
1 2 3 4 5 6 7 8 9
print elements if traversed spirally centre. in above case, answer
5 4 7 8 9 6 3 2 1
being familiar printing array in inward spiral, suggested stacking elements , popping them later, told otherwise.
note : n not equal m
given nxn matrix (being n odd number), , starting @ center position [n/2, n/2], general path generate spiral is:
move left 1 position move down 1 position move right 1 2 positions move 1 2 positions move left 1 3 positions move down 1 3 positions move right 1 4 positions move 1 4 positions ...
there pattern can follow.
edit after edition of op's question
if matrix nxm n != m
or n or m even, first have clarify in question behavior expect when reach 1 of edges of matrix: stop? go on ignoring positions outside matrix?
Comments
Post a Comment