LeetCode 498. Diagonal Traverse
Given an m x n
matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
method
储备知识:mat[i][j]
对应的对角线就是i+j
i+j
是偶数:左下->右上,下标变化是i--,j++
i+j
是奇数:右上->左下,下标变化是i++,j--
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<int> res;
for (int i = 0; i < n + m - 1; i++) {
int x = 0, y = 0;
if (i % 2 == 0) {
x = i < n ? i : n - 1; // 是否超过行数
y = i - x;
while (x >= 0 && y < m) {
res.push_back(mat[x][y]);
x--, y++;
}
}
else {
y = i < m ? i : m - 1; // 是否超过列数
x = i - y;
while (x < n && y >= 0) {
res.push_back(mat[x][y]);
x++, y--;
}
}
}
return res;
}