给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,4,7,5,3,6,8,9]
示例 2:
输入:mat = [[1,2],[3,4]]
输出:[1,2,3,4]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int n = mat.length, m = mat[0].length;
int[] res = new int[n * m];
int idx = 0;
//idr = 1 表示向右上方移动 -1表示左下方
int idr = 1, x = 0, y = 0;
while (idx < n * m) {
res[idx ++] = mat[x][y];
int nx = x, ny = y;
if (idr == 1) {
nx = nx - 1;
ny = ny + 1;
} else {
nx = nx + 1;
ny = ny - 1;
}
//超出界限
if (idx < n * m && (nx < 0 || nx >= n || ny < 0 || ny >= m)) {
if (idr == 1) {
nx = y + 1 < m ? x : x + 1;
ny = y + 1 < m ? y + 1 : y;
} else {
nx = x + 1 < n ? x + 1 : x;
ny = x + 1 < n ? y : y + 1;
}
idr *= -1;
}
x = nx; y = ny;
}
return res;
}
}