顺时针打印:《剑指offer》系列 顺时针打印矩阵(Java)
对角线打印
498. 对角线遍历
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
// 检查空数组
if (mat == null || mat.length == 0) {
return new int[0];
}
int N = mat.length;
int M = mat[0].length;
int[] result = new int[N*M];
int k = 0;
ArrayList<Integer> intermediate = new ArrayList<Integer>();
// 会经历N+M-1次循环
for (int d = 0; d < N + M - 1; d++) {
// 清除数组
intermediate.clear();
//每次行和列的初始值需要关注
int r = d < M ? 0 : d - M + 1;
int c = d < M ? d : M - 1;
while (r < N && c > -1) {
intermediate.add(mat[r][c]);
++r;
--c;
}
// 当d是偶数时,调转顺序
if (d % 2 == 0) {
Collections.reverse(intermediate);
}
for (int i = 0; i < intermediate.size(); i++) {
result[k++] = intermediate.get(i);
}
}
return result;
}
}