Description
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
1 2 3 4 5 6 7
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
1 2 3 4 5 6 7
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]
从外向内螺旋形遍历矩阵。
Solution
列出遍历的四方边界:left
,right
,top
,bottom
;
每次循环时,边界向中间收紧。
在循环中,分别遍历上边
,右边
,底边
,左边
。
|
|