Now, please write a function that traverses the whole square matrix in a spiral.

For example, given this input:

ABCDE

FGHIJ

KLMNO

PQRST

UVWXY

`var = [["A","B","C","D","E"],["F","G","H","I","J"],["K","L","M","N","O"],["P","Q","R","S","T"],["U","V","W","X","Y"]]; = [["A","B","C","D","E"],["F","G","H","I","J"],["K","L","M","N","O"],["P","Q","R","S","T"],["U","V","W","X","Y"]]`

The output of the function would be:

["A","B","C","D","E","J","O","T","Y","X","W","V","U","P","K","F","G","H","I","N","S","R","Q","L","M"]

To traverse the outer layer of the matrix, a solution would be to create 4 loops, one for each edge. To traverse the next most outer layer, a solution would be to create another 4 loops.

In that case, first set of loops could use `0`

and `matrix.lengthlen(matrix)matrix.length - 1`

as offsets, as those indexes represent the beginning and end of the matrix.

The second set of loops could use `1`

and `matrix.lengthlen(matrix)matrix.length - 2`

.

One possible solution to traversing the whole matrix is to have a variable called `offset`

that starts at `0`

, and increment that value each time after the 4 inner loops are traversed. And this outer loop would keep running until `offset`

is greater than `matrix.lengthlen(matrix)matrix.length - 1 - offset`

.

Log In