leetcode_54

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]

Solutions

  1. Straight forward

  2. In each while loop, traverse all items in a certain layer in spiral order starting at the top left item of this layer. More specifically:

    • push the top left top into store vector.

    • Traverse top row, right column, bottom row, left column in the same manner that the first item of the current row or column has been visited.

    • In order to prevent visiting each items twice, ignore the bottom row and the left column when there are only one row or one column in this layer.

Last updated