54_Spiral Matrix
Given a matrix ofmxn
_elements ( m
rows, n
_columns), return all elements of the matrix in spiral order.
Example 1:
Example 2:
Solution
Idea:
Solve the problem from the most outside layer to the center, one layer by one layer
Take the most outside layer as an example, add the first n-1 elements from the first row, then add the first m-1 elements from the last column, then add the first n-1 elements from the last row in reversed order, then add the first m-1 elements from the first column in reversed order. In this order, the number of elements added each time is easy to find.
Have a list represents the directions which are right, down, left, up
After adding one element into the output, set its value to be "used", so that next time if we iterate to "used", we will change direction. The other two situations when needs to change direction are: 1) the row index is out of range; 2) the column index is out of range.
Solution2 :
divide and conquer
Last updated