Spiral Matrix

描述

Given a matrix of m × n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

分析

模拟。

解法1 迭代

  1. // Spiral Matrix
  2. // 时间复杂度O(n^2),空间复杂度O(1)
  3. public class Solution {
  4. public List<Integer> spiralOrder(int[][] matrix) {
  5. List<Integer> result = new ArrayList<>();
  6. if (matrix.length == 0) return result;
  7. int beginX = 0, endX = matrix[0].length - 1;
  8. int beginY = 0, endY = matrix.length - 1;
  9. while (true) {
  10. // From left to right
  11. for (int j = beginX; j <= endX; ++j) result.add(matrix[beginY][j]);
  12. if (++beginY > endY) break;
  13. // From top to bottom
  14. for (int i = beginY; i <= endY; ++i) result.add(matrix[i][endX]);
  15. if (beginX > --endX) break;
  16. // From right to left
  17. for (int j = endX; j >= beginX; --j) result.add(matrix[endY][j]);
  18. if (beginY > --endY) break;
  19. // From bottom to top
  20. for (int i = endY; i >= beginY; --i) result.add(matrix[i][beginX]);
  21. if (++beginX > endX) break;
  22. }
  23. return result;
  24. }
  25. }

解法2 递归

  1. // Spiral Matrix
  2. // 时间复杂度O(n^2),空间复杂度O(1)
  3. public class Solution {
  4. public List<Integer> spiralOrder(int[][] matrix) {
  5. List<Integer> result = new ArrayList<>();
  6. if (matrix.length == 0) return result;
  7. left = 0;
  8. right = matrix[0].length - 1;
  9. up = 0;
  10. down = matrix.length - 1;
  11. dfs(matrix, 0, 0, 0, result);
  12. return result;
  13. }
  14. private void dfs(int[][] matrix, int i, int j, int direction,
  15. List<Integer> result) {
  16. if (i < up || i > down) return;
  17. if (j < left || j > right) return;
  18. result.add(matrix[i][j]);
  19. int nextDirection = (direction + 1) % 4;
  20. switch (direction) {
  21. case 0: // right
  22. if (j < right) {
  23. dfs(matrix, i, j + 1, direction, result);
  24. } else {
  25. ++up;
  26. dfs(matrix, i + 1, j, nextDirection, result);
  27. }
  28. break;
  29. case 1: // down
  30. if (i < down) {
  31. dfs(matrix, i+1, j, direction, result);
  32. } else {
  33. --right;
  34. dfs(matrix, i, j - 1, nextDirection, result);
  35. }
  36. break;
  37. case 2: // left
  38. if (j > left) {
  39. dfs(matrix, i, j - 1, direction, result);
  40. } else {
  41. --down;
  42. dfs(matrix, i - 1, j, nextDirection, result);
  43. }
  44. break;
  45. default: // up
  46. if (i > up) {
  47. dfs(matrix, i - 1, j, direction, result);
  48. } else {
  49. ++left;
  50. dfs(matrix, i, j + 1, nextDirection, result);
  51. }
  52. }
  53. }
  54. private int left;
  55. private int right;
  56. private int up;
  57. private int down;
  58. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/simulation/spiral-matrix.html