给你一个大小为 m x n
的矩阵 mat
,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
暴力模拟
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> ans;
for (int i = 0; i < m + n - 1; i++) {
if (i % 2) {
int x = i < n ? 0 : i - n + 1;
int y = i < n ? i : n - 1;
while (x < m && y >= 0) {
ans.emplace_back(mat[x][y]);
x++;
y--;
}
} else {
int x = i < m ? i : m - 1;
int y = i < m ? 0 : i - m + 1;
while (x >= 0 && y < n) {
ans.emplace_back(mat[x][y]);
x--;
y++;
}
}
}
return ans;
}
};