给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,4,7,5,3,6,8,9]
说明:
- 给定矩阵中的元素总数不会超过 100000 。
C++1
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int x = matrix.size();
int y = matrix[0].size();
vector<int> res(x*y);
vector<vector<int>> dirs{{-1,1}, {1,-1}};
int r = 0, c = 0, k = 0;
for(int i=0;i<x*y;i++){
res[i] = matrix[r][c];
r+=dirs[k][0];
c+=dirs[k][1];
if(r>=x){
r = x-1;
c+=2;
k = 1-k;
}
if(c>=y){
c = y - 1;
r+=2;
k = 1-k;
}
if(r<0){
r=0;
k = 1-k;
}
if(c<0){
c = 0;
k = 1-k;
}
}
return res;
}
};
C++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(), 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;
}
};