[leetcode]498. Diagonal Traverse
[leetcode]498. Diagonal Traverse
Analysis
完了完了 真的要找不到工作了!!!!!苍了天了!!!—— [每天刷题并不难0.0]
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.
注意一下方向的变化以及顺序就行了
Implement
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
vector<int> res;
int m = matrix.size();
if(m == 0)
return res;
int n = matrix[0].size();
int r = 0;
int c = 0;
int d = 0;
int dir[2][2] = {{-1, 1}, {1, -1}};
int cnt = 0;
while(cnt < m*n){
res.push_back(matrix[r][c]);
r += dir[d][0];
c += dir[d][1];
if(r >= m){
r = m-1;
c += 2;
d = 1-d;
}
if(c >= n){
c = n-1;
r += 2;
d = 1-d;
}
if(r < 0){
r = 0;
d = 1-d;
}
if(c < 0){
c = 0;
d = 1-d;
}
cnt++;
}
return res;
}
};