题意:

image.png

解题思路:

  1. 思路:
  2. 1.从左到右,从上到下,从右到左,从下到上依次遍历每一个数
  3. 2.时间复杂度:O(n),每个元素遍历一次

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[][] $matrix
  4. * @return Integer[]
  5. */
  6. function spiralOrder($matrix) {
  7. $ret = [];
  8. if (count($matrix) == 0 || count($matrix[0]) == 0) return $ret;
  9. $top = 0; $bottom = count($matrix) - 1;
  10. $left = 0; $right = count($matrix[0]) - 1;
  11. while (true) {
  12. //from left to right
  13. for ($i = $left; $i <= $right; $i++) {
  14. array_push($ret, $matrix[$top][$i]);
  15. }
  16. $top++;
  17. if ($left > $right || $top > $bottom) break;
  18. //from top to bottom
  19. for ($i = $top; $i <= $bottom; $i++) {
  20. array_push($ret, $matrix[$i][$right]);
  21. }
  22. $right--;
  23. if ($left > $right || $top > $bottom) break;
  24. //from right to left
  25. for ($i = $right; $i >= $left; $i--) {
  26. array_push($ret, $matrix[$bottom][$i]);
  27. }
  28. $bottom--;
  29. if ($left > $right || $top > $bottom) break;
  30. //from bottom to top
  31. for ($i = $bottom; $i >= $top; $i--) {
  32. array_push($ret, $matrix[$i][$left]);
  33. }
  34. $left++;
  35. if ($left > $right || $top > $bottom) break;
  36. }
  37. return $ret;
  38. }
  39. }

GO代码实现:

  1. func spiralOrder(matrix [][]int) []int {
  2. if len(matrix) == 0 {
  3. return nil
  4. }
  5. step := 0
  6. size := len(matrix) * len(matrix[0])
  7. top, bottom, left, right := 0, len(matrix) - 1, 0, len(matrix[0]) - 1
  8. result := make([]int, size)
  9. for step < size {
  10. for i := left; i <= right && step < size; i++ {
  11. result[step] = matrix[top][i]
  12. step++
  13. }
  14. top++
  15. for i := top; i <= bottom && step < size; i++ {
  16. result[step] = matrix[i][right]
  17. step++
  18. }
  19. right--
  20. for i := right; i >= left && step < size; i-- {
  21. result[step] = matrix[bottom][i]
  22. step++
  23. }
  24. bottom--
  25. for i := bottom; i >= top && step < size; i-- {
  26. result[step] = matrix[i][left]
  27. step++
  28. }
  29. left++
  30. }
  31. return result
  32. }