https://leetcode.com/problems/diagonal-traverse/description/
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if(matrix.size() == 0) return {};
int M = matrix.size();
int N = matrix[0].size();
int K = M+N-2;
vector<int> res;
for(int k=0; k<=K; k++) {
int i=0, j=0, d;
if(k%2 == 0) {
i = k<M? k:M-1;
j = k-i;
d = -1;
}
else {
j = k<N? k:N-1;
i = k-j;
d = 1;
}
while(i>=0 && i<M && j>=0 && j<N) {
res.push_back(matrix[i][j]);
i += d;
j -= d;
}
}
return res;
}
No comments:
Post a Comment