Click here to Skip to main content
15,867,950 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Comments
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 ...

1 solution

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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900