前言
力扣第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<Integer> queue = new LinkedList<>();
HashSet<Integer> set = new HashSet<>(); // 避免同一节点重复打印
queue.add(0);
set.add(0);
while (!queue.isEmpty()) { //层序遍历
LinkedList<Integer> 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<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
}else {// 对temp进行降序排序
Collections.sort(temp, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
}
isFlag = ! isFlag; // 交替转换打印顺序
queue = temp;
}
return res;
}
}