-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdiagonal_traverse.cpp
37 lines (31 loc) · 956 Bytes
/
diagonal_traverse.cpp
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
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if(matrix.size() == 0) return {};
int row = 0, col = 0, k = 0;
int m = matrix.size(), n = matrix[0].size();
vector<int> result;
for(int i=0; i<(m*n); i++){
result.push_back(matrix[row][col]);
if((row+col) % 2 == 0){ //even diagonal
if(col == n-1) row++;
else if(row == 0) col++;
else{
row--;
col++;
}
}
else{ //odd diagonal
if(row == m-1)
col++;
else if(col == 0)
row++;
else{
col--;
row++;
}
}
}
return result;
}
};