一、题目内容

image.png

二、题解

解法1:

思路

模拟法。
新建二维数组记录是否已经打印过、新建二维数组记录下一步的方向。

代码

  1. class Solution {
  2. public int[] spiralOrder(int[][] matrix) {
  3. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  4. return new int[0];
  5. }
  6. int rows = matrix.length;
  7. int columns = matrix[0].length;
  8. int[][] done = new int[rows][columns];
  9. int total = rows * columns;
  10. int[] res = new int[total];
  11. int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
  12. int directIndex = 0;
  13. int row = 0, colum = 0;
  14. for (int i = 0; i < total; i++) {
  15. res[i] = matrix[row][colum];
  16. done[row][colum] = 1;
  17. int nextRow = row + directions[directIndex][0];
  18. int nextColumn = colum + directions[directIndex][1];
  19. // 行溢出或者行遍历结束或者列溢出或者列遍历结束或者下一个节点已经遍历过
  20. if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || done[nextRow][nextColumn] == 1) {
  21. directIndex = (directIndex + 1) % 4;
  22. }
  23. row += directions[directIndex][0];
  24. colum += directions[directIndex][1];
  25. }
  26. return res;
  27. }
  28. }