This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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

For example,

Given the following matrix:

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

You should return `[1,2,3,6,9,8,7,4,5]`

.

b'

\n\n#### Approach #1: Simulation [Accepted]

\n

\n#### Approach #2: Layer-by-Layer [Accepted]

\n\n

\n

'
**Intuition**

Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would go out of bounds or into a cell that was previously visited.

\n**Algorithm**

Let the array have rows and columns. denotes that the cell on the-th row and -th column was previously visited. Our current position is , facing direction , and we want to visit x total cells.

\nAs we move through the matrix, our candidate next position is . If the candidate is in the bounds of the matrix and unseen, then it becomes our next position; otherwise, our next position is the one after performing a clockwise turn.

\n\n**Complexity Analysis**

- \n
- \n
Time Complexity: , where is the total number of elements in the input matrix. We add every element in the matrix to our final answer.

\n \n - \n
Space Complexity: , the information stored in

\n`seen`

and in`ans`

. \n

\n

**Intuition**

The answer will be all the elements in clockwise order from the first-outer layer, followed by the elements from the second-outer layer, and so on.

\n**Algorithm**

We define the -th outer layer of a matrix as all elements that have minimum distance to some border equal to . For example, the following matrix has all elements in the first-outer layer equal to 1, all elements in the second-outer layer equal to 2, and all elements in the third-outer layer equal to 3.

\n[[1, 1, 1, 1, 1, 1, 1],\n [1, 2, 2, 2, 2, 2, 1],\n [1, 2, 3, 3, 3, 2, 1],\n [1, 2, 2, 2, 2, 2, 1],\n [1, 1, 1, 1, 1, 1, 1]]\n

For each outer layer, we want to iterate through its elements in clockwise order starting from the top left corner. Suppose the current outer layer has top-left coordinates and bottom-right coordinates .

\nThen, the top row is the set of elements for , in that order. The rest of the right side is the set of elements for , in that order. Then, if there are four sides to this layer (ie., and ), we iterate through the bottom side and left side as shown in the solutions below.

\n\n\n**Complexity Analysis**

- \n
- \n
Time Complexity: , where is the total number of elements in the input matrix. We add every element in the matrix to our final answer.

\n \n - \n
Space Complexity: , the information stored in

\n`ans`

. \n

\n

Analysis written by: @awice

\n