-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiagonal_Traverse.cpp
More file actions
45 lines (40 loc) · 953 Bytes
/
Copy pathDiagonal_Traverse.cpp
File metadata and controls
45 lines (40 loc) · 953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
498. Diagonal Traverse
Medium
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]
*/
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
vector<int> r;
int m = matrix.size();
if(m==0) return r;
int n = matrix[0].size();
vector<vector<int>> res(m+n-1);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
res[i+j].push_back(matrix[i][j]);
}
}
int k = m+n-1;
for(int i=0;i<k;i++){
if(i%2==0){
reverse(res[i].begin(), res[i].end());
}
}
for( auto el : res){
for(int val : el){
r.push_back(val);
}
}
return r;
}
};