LeetCode 498 对角线遍历 Java实现

LeetCode 498
LeetCode 498 对角线遍历 Java实现_第1张图片

题目

给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。

示例:

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

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

解释:
LeetCode 498 对角线遍历 Java实现_第2张图片

说明:

给定矩阵中的元素总数不会超过 100000 。

代码

class Solution {
     
    public int[] findDiagonalOrder(int[][] matrix) {
     
        int x = matrix.length;
        //行数
        if(x == 0){
     
            return new int[]{
     };
        }
        int y = matrix[0].length;
        //列数
        int[] ans = new int[x*y];
        //储存答案的数组
        int sum = x + y - 1;
        //求行与列的最大值
        int i = 0,j = 0;
        List list1 = new ArrayList();
        //声明链表用于存储答案
        for(int count = 0; count < sum; count++){
     
            List list2 = new ArrayList();
            //每次声明一个新的链表用于添加到存储答案的列表(因为遍历的时候需要反向
            if(count >= x - 1){
     
                //如果行小于列那么就把行设定到x-1进行遍历
                i = x - 1;
                j =count - x +1 ;
            }
            else {
     
                i = count;
                j = 0;
            }
            for(; i >= 0 && j <= y-1 ; i--,j++){
     
            //每次都是从左下到右上的遍历
                list2.add(matrix[i][j]);
            }
            if(count % 2 == 1){
     
            //每遍历两次反向一次
                Collections.reverse(list2);
            }
            for (int w = 0; w < list2.size();w++){
     
                list1.add(list2.get(w));
            }
        }
        for (int w = 0; w < list1.size();w++){
     
            ans[w] = (int)list1.get(w);
        }

        return ans;
    }
}```

你可能感兴趣的:(LeetCode,leetcode,算法)