给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。

    示例 1:
    image.png

    输入: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


    1. class Solution {
    2. public int[] findDiagonalOrder(int[][] mat) {
    3. int n = mat.length, m = mat[0].length;
    4. int[] res = new int[n * m];
    5. int idx = 0;
    6. //idr = 1 表示向右上方移动 -1表示左下方
    7. int idr = 1, x = 0, y = 0;
    8. while (idx < n * m) {
    9. res[idx ++] = mat[x][y];
    10. int nx = x, ny = y;
    11. if (idr == 1) {
    12. nx = nx - 1;
    13. ny = ny + 1;
    14. } else {
    15. nx = nx + 1;
    16. ny = ny - 1;
    17. }
    18. //超出界限
    19. if (idx < n * m && (nx < 0 || nx >= n || ny < 0 || ny >= m)) {
    20. if (idr == 1) {
    21. nx = y + 1 < m ? x : x + 1;
    22. ny = y + 1 < m ? y + 1 : y;
    23. } else {
    24. nx = x + 1 < n ? x + 1 : x;
    25. ny = x + 1 < n ? y : y + 1;
    26. }
    27. idr *= -1;
    28. }
    29. x = nx; y = ny;
    30. }
    31. return res;
    32. }
    33. }