-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path498.diagonal-traverse.cpp
More file actions
53 lines (37 loc) · 949 Bytes
/
498.diagonal-traverse.cpp
File metadata and controls
53 lines (37 loc) · 949 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
46
47
48
49
50
51
52
53
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
vector<int> result;
int direction = 1;
int x = 0;
int y = 0;
int m = mat.size();
int n = mat[0].size();
while(true) {
if(x >= n || y >= m || y < 0 || x < 0) direction *= -1;
if(x >= n) {
x = n - 1;
y += 2;
}
if(y >= m) {
y = m - 1;
x += 2;
}
if(x < 0) {
x = 0;
}
if(y < 0) {
y = 0;
}
x = max(x, 0);
y = max(y, 0);
x = min(x, n - 1);
y = min(y, m - 1);
result.push_back(mat[y][x]);
if(y == m - 1 && x == n - 1) break;
y -= direction;
x += direction;
}
return result;
}
};