题目:
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.
思路:
题目的难度不大,但是需要注意各种边界情况。读者可以重点研究一下for循环里面的四个if语句。算法的时间复杂度是O(m*n),空间复杂度是O(1)。
代码:
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int row_num = matrix.size(), col_num = matrix[0].size();
vector<int> ret;
int row = 0, col = 0, d = 0;
vector<vector<int>> dirs = {{-1, 1}, {1, -1}};
for (int i = 0; i < row_num * col_num; ++i) {
ret.push_back(matrix[row][col]);
row += dirs[d][0], col += dirs[d][1];
if (row >= row_num) { // from down to up
row = row_num - 1, col += 2, d = 1 - d;
}
if (col >= col_num) { // from up to down
col = col_num - 1, row += 2, d = 1 - d;
}
if (row < 0) { // from up to down
row = 0, d = 1 - d;
}
if (col < 0) { // from down to up
col = 0, d = 1 - d;
}
}
return ret;
}
};