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

Java

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).

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of