栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【LeetCode】498.对角线遍历,使用广度优先搜索进行解题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【LeetCode】498.对角线遍历,使用广度优先搜索进行解题

前言

力扣第498道题:对角线遍历,此题的题解中基本都是寻找坐标变化规律进行解题,没有用到数据结构中的知识进行解题,在此提出一种广度优先搜索遍历方法实现层序遍历进行解题。


一、基本思路

对于矩阵我们将其顺时针旋转90度,便可将其视为二叉树,即可实现层序遍历。需要注意的是:
(1)层序遍历时会有重复节点多次打印,需要避免,代码中使用HashSet存储已经打印过的变量以避免重复打印;
(2)注意打印顺序,代码中使用isFalg变量来控制打印顺序;

矩阵旋转90度:即可将矩阵视为根节点为坐标(0,0)的二叉树

二、代码实现
class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        if (mat.length == 0)
            return new int[0];

        int[] res = new int[mat.length * mat[0].length];
        int index = 0;
        boolean isFlag = true;

        int row = mat.length;
        int column = mat[0].length;

        LinkedList queue = new LinkedList<>();
        HashSet set = new HashSet<>();  // 避免同一节点重复打印
        queue.add(0);
        set.add(0);

        while (!queue.isEmpty()) { //层序遍历
            LinkedList temp = new LinkedList<>();
            while (! queue.isEmpty()){
                int num = queue.poll();
                int i = num / column; // 获取横坐标
                int j = num % column; // 获取纵坐标
                res[index++] = mat[i][j];
                if (j + 1 < column && !set.contains(column*i + j + 1)){ // 访问右子节点
                    int tempNum = column*i + j + 1;
                    temp.addLast(tempNum);
                    set.add(tempNum);
                }
                if (i + 1 < row && !set.contains(column*(i+1) + j)){// 访问左子节点
                    int tempNum = column*i + j + 1;
                    temp.addLast(column*(i+1) + j);
                    set.add(column*(i+1) + j);
                }
            }
            if (isFlag){ // 对temp进行升序排序
                Collections.sort(temp, new Comparator() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o1 - o2;
                    }
                });
            }else {// 对temp进行降序排序
                Collections.sort(temp, new Comparator() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o2 - o1;
                    }
                });
            }
            isFlag = ! isFlag; // 交替转换打印顺序
            queue = temp;
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号