Spiral Traversal Matrix

mediumGreedyconstructive algorithm

You are given a $$$2$$$-dimensional matrix $$$A$$$ consisting of $$$n$$$ rows and $$$m$$$ columns. Your task is to print the elements of the matrix in spiral order starting from the top-left corner.

The spiral order of a matrix is obtained by traversing the matrix in a clockwise spiral direction — first right, then down, then left, then up, and so on — until all elements are visited.

Input Format:

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of rows and columns of the matrix.

Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,j}$$$ ($$$-10^9 \le a_{i,j} \le 10^9$$$) — the elements of the matrix.

Output Format:

Print a single line containing $$$n \cdot m$$$ space-separated integers — the elements of the matrix in spiral order.

Examples:

Example 1:

Input:

3 3
1 2 3
8 9 4
7 6 5

Output:

1 2 3 4 5 6 7 8 9

Note:

Example 1:

The spiral traversal starts from the top-left element and proceeds as follows:

  • Move right: $$$1 \ 2 \ 3$$$
  • Move down: $$$4 \ 5$$$
  • Move left: $$$6 \ 7$$$
  • Move up: $$$8$$$
  • Move right: $$$9$$$

Thus, the spiral order is: $$$1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9$$$

Code

Loading Editor...