# 498. Diagonal Traverse

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]
Explanation:
``````

Note:

1. The total number of elements of the given matrix will not exceed 10,000.

``````class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size(), r = 0, c = 0, k = 0;
vector<int> res(m * n);
vector<vector<int>> dirs{{-1,1}, {1,-1}};
for (int i = 0; i < m * n; ++i) {
res[i] = matrix[r][c];
r += dirs[k][0];
c += dirs[k][1];
if (r >= m) {r = m - 1; c += 2; k = 1 - k;}
if (c >= n) {c = n - 1; r += 2; k = 1 - k;}
if (r < 0) {r = 0; k = 1 - k;}
if (c < 0) {c = 0; k = 1 - k;}
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size(), r = 0, c = 0;
vector<int> res(m * n);
for (int i = 0; i < m * n; ++i) {
res[i] = matrix[r][c];
if ((r + c) % 2 == 0) {
if (c == n - 1) {++r;}
else if (r == 0) {++c;}
else {--r; ++c;}
} else {
if (r == m - 1) {++c;}
else if (c == 0) {++r;}
else {++r; --c;}
}
}
return res;
}
};
``````

[0,0] -> [0,1],[1,0] -> [2,0],[1,1],[0,2] -> [1,2],[2,1] -> [2,2]

``````class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size(), k = 0;
vector<int> res(m * n);
for (int i = 0; i < m + n - 1; ++i) {
int low = max(0, i - n + 1), high = min(i, m - 1);
if (i % 2 == 0) {
for (int j = high; j >= low; --j) {
res[k++] = matrix[j][i - j];
}
} else {
for (int j = low; j <= high; ++j) {
res[k++] = matrix[j][i - j];
}
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size(), k = 0;
vector<int> res;
for (int k = 0; k < m + n - 1; ++k) {
int delta = 1 - 2 * (k % 2 == 0);
int ii = (m - 1) * (k % 2 == 0);
int jj = (n - 1) * (k % 2 == 0);
for (int i = ii; i >= 0 && i < m; i += delta) {
for (int j = jj; j >= 0 && j < n; j += delta) {
if (i + j == k) {
res.push_back(matrix[i][j]);
}
}
}
}
return res;
}
};
``````

https://discuss.leetcode.com/topic/77866/short-bf-solution

https://discuss.leetcode.com/topic/77865/concise-java-solution/2

https://discuss.leetcode.com/topic/77862/my-8ms-short-solution-9line

https://discuss.leetcode.com/topic/77937/java-15-lines-without-using-boolean

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation