Given a matrix of
m x n
elements, where
m
is the number of rows and
n
is the number of columns. Write a program to return all elements of the matrix in spiral order.
Example 1
Input:
[
[1, 2],
[3, 4]
]
Output: [1, 2, 4, 3]
Explanation: In the above example, the elements of first row i.e., [1, 2] are taken first in the output, then in continuity the 2nd column remaining element is taken i.e. [4], and then in continuity the 2nd row remaining element is taken i.e., [3]. Thus, we get [1, 2, 4, 3] as output.
Example 2
Input:
[
[5, 8, 3],
[3, 8, 6],
[4, 7, 3]
]
Output: [5, 8, 3, 6, 3, 7, 4, 3, 8]
Explanation: In the above example, the elements of first row i.e., [5, 8, 3] are taken first in the output, then in continuity the 3rd column remaining elements are taken i.e. [6, 3], then in continuity the 3rd row elements are taken i.e., [7, 4], and at last in continuity the remaining elements of the 2nd row are taken i.e., [3, 8]. Thus, we get [5, 8, 3, 6, 3, 7, 4, 3, 8] as output.