# Iterating all diagonal slices of a matrix

## Main Question or Discussion Point

I'm writing something in Java, (but the language doesn't really matter for this problem), and I can't figure out any way to do this efficiently.

I have some character array with a bunch of stuff in it, and I need to slice it into it's diagonals, for example:

[a,b,c; d,e,f; g,h,i]

becomes: [a], [d,b], [g,e,c], [f,h], (this is just one "direction" of slicing)

But the problem is, the character array is mxn with unknown dimensions!

No matter how I nestle loops, I just can't make this happen. Tomorrow morning I am going to try 3 cases, mxn where m=n, m>n, and m<n, but then it seems I must break each of those cases into 2-3 other parts to iterate through, and it blows out of proportion from there.

Any idea how I could accomplish this task?

You start at $(i, j) = (i_0, 0)$ or $(i, j) = (0, j_0)$ and in every iteration send $(i, j) \mapsto (i \pm 1, j \pm 1)$ (with the two $\pm$ chosen depending on the direction you want to run) until one of the variables runs out of bounds (i.e. $i < 0$, $i \ge m$, $j < 0$ or $j \ge n$).