498. Diagonal Traverse
https://leetcode.com/problems/diagonal-traverse/description/
/*
* @lc app=leetcode id=498 lang=cpp
*
* [498] Diagonal Traverse
*/
// @lc code=start
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
vector<int> res(M * N, 0);
for (int i = 0, x = 0, y = 0, c = 0; i < M * N; ++i) {
res[c++] = matrix[x][y];
if ((x + y) % 2 == 0) {
if (y == N - 1) ++x;
else if (x == 0) ++y;
else {
--x;
++y;
}
} else {
if (x == M - 1) ++y;
else if (y == 0) ++x;
else {
++x;
--y;
}
}
}
return res;
}
};
// @lc code=end
Last updated