Skip to content

Latest commit

 

History

History
65 lines (52 loc) · 1.39 KB

0054-spiral-matrix.adoc

File metadata and controls

65 lines (52 loc) · 1.39 KB

54. Spiral Matrix

{leetcode}/problems/spiral-matrix/[LeetCode - Spiral Matrix^]

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

Example 1:

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

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

思路分析

从回溯思想得到启发,使用递归来逐层推进。每次方法调用只负责指定层的遍历,向里推进层次的工作,交给递归来完成。这样避免了复杂的判断。

{image_attr}
一刷
link:{sourcedir}/_0054_SpiralMatrix.java[role=include]
二刷
link:{sourcedir}/_0054_SpiralMatrix_2.java[role=include]