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:
The total number of elements of the given matrix will not exceed 10,000.
方法1:
思路:
根据奇偶性来判断遍历的方向,每一条线满足i + j = k, k的上界是m + n - 2。
易错点:
- 只有当i,j完全满足边界条件时才推入结果,注意上面的对角线有划过空格点的情况,比如(0, 3),i 确实是从0开始,但 j 已经超出边界了。
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(), total = m + n - 2;
vector<int> result;
for (int k = 0; k <= total; k++) {
if (k % 2) {
for (int i = 0, j = k - i; i < m && j >= 0; i++, j--) {
if (j < n)
result.push_back({matrix[i][j]});
}
}
else {
for (int j = 0, i = k - j; j < n && i >= 0; j++, i--) {
if (i < m)
result.push_back({matrix[i][j]});
}
}
}
return result;
}
};