[LeetCode] Diagonal Traverse

498. Diagonal Traverse

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

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
class Solution {
bool hasNext(bool dir, int y, int x, int n, int m) {
if(dir) y--, x++;
else y++, x--;
return 0 <= y && y < n && 0 <= x && x < m;
}
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int y(0), x(0), n(mat.size()), m(mat[0].size());
vector<int> res;
bool dir(true);
res.reserve(m*n);
while (y != n - 1 || x != m - 1) {
res.push_back(mat[y][x]);
if(hasNext(dir, y, x, n, m)) {
if(dir) y--, x++;
else y++, x--;
} else {
if((dir && x == m - 1) || (!dir && y != n - 1)) y++;
else x++;
dir = !dir;
}
}
res.push_back(mat[y][x]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/20/PS/LeetCode/diagonal-traverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.