Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
#include <iostream>
using namespace std;
#define M 5
#define N 4
int main()
{
int a[M][N]={
1, 2, 3, 4,
5, 6, 7, 8,
9,10,11,12,
13,14,15,16,
17,18,19,20
};
int i=0,j=0;
cout<<a[i][j]<<endl;
while(i<M-1||j<N-1){
if(j<N-1){
cout<<a[i][++j]<<endl;
}else if(i<M-1){
cout<<a[i][j]<<endl;
}
while(i<M-1&&j>0){
cout<<a[++i][--j]<<endl;
}
if(i<M-1){
cout<<a[++i][j]<<endl;
}else if(j<N-1){
cout<<a[i][++j]<<endl;
}
while(i>0&&j<N-1){
cout<<a[--i][++j]<<endl;
}
}
}