Log In

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

For example, given this input:
ABCDE
FGHIJ
KLMNO
PQRST
UVWXY

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 - 1 as offsets, as those indexes represent the beginning and end of the matrix.

The second set of loops could use 1 and - 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 - 1 - offset.

Sign Up or Log In to access the code editor and answer the question!
Log In