Here's the Python version:
def reverse_diagonal_traversal(matrix):
side = len(matrix) + 1
iterations = side - 1
for i in range(1, side):
for j in range(i):
yield matrix[j][iterations + j - i]
for i in range(side - 2, 0, -1):
for j in range(i):
yield matrix[iterations + j - i][j]
def test(side):
matrix = [range(i * side, side + i * side) for i in range(side)]
print matrix
for i in reverse_diagonal_traversal(matrix):
print i
Writing this in C would require too much code dealing with memory (de)allocation / printing, which isn't really part of this problem. I'd imagine that porting the above to C won't be a problem.
The idea behind the code is that you need to produce iterations of 1..N
length until you reach the main diagonal, and then N-1..1
. In the first half, you'd have to select the row at N
at the first step of the iteration, and then N-i
for each value of i
in the iteration. You'd select the column starting at nth iteration - length of iteration
, and then for each iteration step you'd increment that by one.
Finally, I'm not sure this is the most "elegant" solution (maybe you can do it in just half the code), but I couldn't find a good way to do that.