Print diagonal elements of the matrix having positive slope

Given a M x N matrix, print all its diagonal elements having positive slope.


 

For example,


Input:

diagonal-matrix

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6
7 7 7
8 8
9

 


 

The idea is to start from each cell of first column of the matrix to print / diagonal for upper-left half of the matrix. Similarly after upper-left half, we start from each cell of the last row to print / diagonal for lower-right half of the matrix.

C++

Download   Run Code

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6
7 7 7
8 8
9

 
The time complexity of above solution is O(M*N) and auxiliary space used by the program is O(1).

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz