题目

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

  1. Input:
  2. [
  3. [ 1, 2, 3 ],
  4. [ 4, 5, 6 ],
  5. [ 7, 8, 9 ]
  6. ]
  7. Output: [1,2,4,7,5,3,6,8,9]

Explanation:

image.png

Note:

The total number of elements of the given matrix will not exceed 10,000.


题意

按照对角线方向遍历矩阵。

思路

可以按照图示路线进行模拟,或者直接每次都按照右上到左下的顺序遍历,并把奇数次的遍历翻转过来:
image.png


代码实现

Java

模拟

  1. class Solution {
  2. public int[] findDiagonalOrder(int[][] matrix) {
  3. if (matrix.length == 0) {
  4. return new int[0];
  5. }
  6. int m = matrix.length, n = matrix[0].length;
  7. int[] ans = new int[m * n];
  8. int x = 0, y = 0;
  9. int xStep = -1, yStep = 1;
  10. for (int i = 0; i < m * n; i++) {
  11. ans[i] = matrix[x][y];
  12. int nextX = x + xStep, nextY = y + yStep;
  13. if (nextX == -1 && nextY == n) {
  14. // 当前在右上角,且要继续向右上走
  15. x = x + 1;
  16. } else if (nextX == -1 || nextY == n) {
  17. // 当前在上边界或右边界,且要继续向右上走
  18. x = nextX == -1 ? x : x + 1;
  19. y = nextY == n ? y : y + 1;
  20. } else if (nextX == m && nextY == -1) {
  21. // 当前在左下角,且要继续向左下走
  22. y = y + 1;
  23. } else if (nextX == m || nextY == -1) {
  24. // 当前在左边界或下边界,且要继续向左下走
  25. x = nextX == m ? x : x + 1;
  26. y = nextY == -1 ? y : y + 1;
  27. } else {
  28. x = nextX;
  29. y = nextY;
  30. }
  31. if (nextX == -1 || nextY == -1 || nextX == m || nextY == n) {
  32. xStep = -xStep;
  33. yStep = -yStep;
  34. }
  35. }
  36. return ans;
  37. }
  38. }

翻转

  1. class Solution {
  2. public int[] findDiagonalOrder(int[][] matrix) {
  3. if (matrix.length == 0) {
  4. return new int[0];
  5. }
  6. int m = matrix.length, n = matrix[0].length;
  7. int[] ans = new int[m * n];
  8. int index = 0;
  9. for (int i = 0; i < m + n - 1; i++) {
  10. int x = i < n ? 0 : i - n + 1, y = i < n ? i : n - 1;
  11. int start = index;
  12. while (x < m && y >= 0) {
  13. ans[index++] = matrix[x++][y--];
  14. }
  15. if (i % 2 == 0) {
  16. reverse(ans, start, index - 1);
  17. }
  18. }
  19. return ans;
  20. }
  21. private void reverse(int[] A, int start, int end) {
  22. while (start < end) {
  23. int tmp = A[start];
  24. A[start++] = A[end];
  25. A[end--] = tmp;
  26. }
  27. }
  28. }