My approach
Hi there!
Look at my approach for solving this problem.
I`m using 1-dimensional representation of digital matrix. In example matrix M below:
A11, A12, A13, A14
(M) = A21, A22, A23, A24
A31, A32, A33, A34
A41, A42, A43, A44
transforms to the vector V:
V = (A11, A12, A13, A14, A21, A22, A23, A24, A31, A32, A33, A34, A41, A42, A43, A44)
(array of integers in my C++ implementation).
Than point out the order in which elements of matrix M should appears in result:
(1) (3) (6) (10) (2) (5) (9) (13) (4) (8) (12) (15) (7) (11) (14) (16)
A11, A12, A13, A14, A21, A22, A23, A24, A31, A32, A33, A34, A41, A42, A43, A44, where
values in brackets are elements serial numbers in result.
Onwards take a pencil and draw a curves between elements in desired order:
(1) (3) (6) (10) (2) (5) (9) (13) (4) (8) (12) (15) (7) (11) (14) (16)
A11, A12, A13, A14, A21, A22, A23, A24, A31, A32, A33, A34, A41, A42, A43, A44
|___↑_|__↑_________↑ | ↑ | ↑ |
|_|__|___________| | | | |
|__|______________|_|____________| |
| |_|______________|
|________________| ... and so on
In example above 6 elements ordered by curves connections. It should be observed that
it`s possible to fix sequence of actions using numeric relative offsets. See below:
Step 1) +4 (+4 is offset (in elements) of first element A11);
Step 2) -3 (-3 is offset of element, obtained in step 1);
Step 3) +7 (+7 is offset of element, obtained in previous step and so on);
Step 4) -3
Step 5) -3
Step 6) +10
Step 7) -3
Step 8) -3
Step 9) -3
Step 10) +10
Step 11) -3
Step 12) -3
Step 13) +7
Step 14) -3
Step 15) +4
Halves of steps sequence are simmetrical. Sequence contains two operation type: forward offset and backward offset (all offset are relative). Value of backward always equals to (side of matrix - 1). Value of forward offset different on difference steps. On first and last steps it`s equal to side size. On other steps it`s increased or decreased (above or below of middle steps) on value (side of matrix - 1).
Forward steps amount is always equals to 2 x (side-1). Amount of backwards steps are 1 on first forward step, 2 on second and so on toward the middle of iterations. After middle backwards steps amount decreased by 1 on each iterations except last. On last iterations it`s not backwards steps.
This algorithm has simple (not required complex data structures) implementation on various language.
Thank you for your attention and Good luck!
P.S. Sorry for my English =)
P.P.S. Graphical representation of algorithms steps is distorted because when message is sent any occurance of double, triple and so on spaces are replaced on one space character :(
Edited by author 13.09.2011 15:09