The Challenge
The shortest code by character count that takes a single input integer N
(N >= 3) and returns an array of indices that when iterated would traverse an N
xN
matrix according to the JPEG "zigzag" scan pattern. The following is an example traversal over an 8x8 matrixsrc:
Examples
(The middle matrix is not part of the input or output, just a representation of the NxN matrix the input represents.)
1 2 3
(Input) 3 --> 4 5 6 --> 1 2 4 7 5 3 6 8 9 (Output)
7 8 9
1 2 3 4
(Input) 4 --> 5 6 7 8 --> 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16 (Output)
9 10 11 12
13 14 15 16
Notes
- The resulting array's base should be appropriate for your language (e.g., Matlab arrays are 1-based, C++ arrays are 0-based).
- This is related to this question.
Bonus
Extend your answer to take two inputs N
and M
(N, M >=3) and perform the same scan over an N
xM
matrix. (In this case N
would be the number of columns and M
the number of rows.)
Bonus Examples
1 2 3 4
(Input) 4 3 --> 5 6 7 8 --> 1 2 5 9 6 3 4 7 10 11 8 12 (Output)
9 10 11 12
1 2 3
(Input) 3 4 --> 4 5 6 --> 1 2 4 7 5 3 6 8 10 11 9 12 (Output)
7 8 9
10 11 12