avatar

LeetCode-498 对角线遍历

📝题目

1
2
3
4
5
6
7
8
9
10
11
12
给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。

示例:

输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

输出: [1,2,4,7,5,3,6,8,9]


📝思路

找规律,分奇偶讨论。

📝题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
vector<int> result;
if (row <= 0) return result;
int column = matrix[0].size();

for (int i = 0; i < row; ++i){
if (i % 2 == 0){
for (int j = 0; j < column; ++j)
if (i - j >= 0) result.push_back(matrix[i-j][j]);
}
else {
for (int j = column-1; j >= 0; --j)
if (i - j >= 0) result.push_back(matrix[i-j][j]);
}
}

for (int j = 1; j < column; ++j){
if ((row+j) % 2 == 1){
for (int i = 0; i < column-j; ++i)
if (row-1-i >= 0) result.push_back(matrix[row-1-i][j+i]);
}
else {
for (int i = column-j-1; i >= 0; --i)
if (row-1-i >= 0) result.push_back(matrix[row-1-i][j+i]);
}
}
return result;
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2020/04/26/LeetCode-498-%E5%AF%B9%E8%A7%92%E7%BA%BF%E9%81%8D%E5%8E%86/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.