LeetCode498-对角线遍历

题目描述

给你一个大小为 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]

解析

以一个变量 direction 表示当前遍历方向,往右上时令 direction = 1,此时使用 rowIndex -= direction; colIndex += direction 进行遍历;当 rowIndex == 0 || rowIndex == m - 1 说明到达上边界,此时需要调转方向,令 direction = -direction,依然保持 rowIndex -= direction; colIndex += direction 即可向左下。当 colIndex = 0 || colIndex == n - 1 时说明到达下边界,重复上面的处理方式,直到 rowIndex == m || colIndex == n

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static int[] findDiagonalOrder(int[][] mat) {  
int m = mat.length;
int n = mat[0].length;

int rowIndex = 0;
int colIndex = 0;
int direction = 1;
List<Integer> result = new ArrayList<>();
while (rowIndex < m && colIndex < n) {
result.add(mat[rowIndex][colIndex]);
if ((rowIndex == 0 && colIndex < n - 1 && direction == 1) || (rowIndex == m - 1 && direction == -1)) {
direction = -direction;
colIndex += 1;
continue;
} else if ((colIndex == 0 && rowIndex < m - 1 && direction == -1) || (colIndex == n - 1 && direction == 1)) {
direction = -direction;
rowIndex += 1;
continue;
}
colIndex += direction;
rowIndex -= direction;
}
return result.stream().mapToInt(Integer::intValue).toArray();
}