15,669,039 members
See more:
```I'm looking for a C++ way using vector to get all the diagonals of a (square) matrix, represented as a 2d vector.

matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]]

But I have trouble coming up with a way to generate all the diagonals. The output I'm looking for is:

"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".```

What I have tried:

I tried but I can only print the elements of the main diagonal. Could someone show how to print all the diagonal elements.
Posted
Updated 28-Mar-20 0:21am
John R. Shaw 28-Mar-20 1:42am
Interesting. But do not post home work questions here. Grab a pencil and paper and figure it out.
-OR-
I could put on a blind fold and see if I could do it.
Richard MacCutchan 28-Mar-20 4:46am
You just need to start from every relevant point in the matrix, and traverse the diagonal from that point. So starting in column1 go down the rows and follow each. Then follow each daigonal from column2, column3 ...

## Solution 1

A diagonal starting at `(row,0)` includes all items `(row+k,k)` where `k=0,1,.., ROWS-row-1`.
In a similar way, a diagonal starting at `(0,col)` includes all items `(k,col+k)` where `k=0, 1, .., COLS-col-1`.

The task is competed if you iterate on rows:
`row = N-1,N-2,..,0`
and columns:
`col = 1, 2, .., COLS-1`