Matrix Spiral Print
EasyPractice library · +10 XPmatrixtraversal
Given an N x M matrix of integers, print its elements in a spiral order, starting from the top-left corner and moving clockwise. The spiral should fill the entire matrix.
Input
The first line contains two integers N and M (the dimensions of the matrix). The next N lines each contain M space-separated integers, representing the matrix elements.
Output
Print the elements of the matrix in spiral order, separated by spaces, on a single line.
Constraints
1 <= N, M <= 100; -1000 <= matrix[i][j] <= 1000
Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
3 3 1 2 3 4 5 6 7 8 9
Output
1 2 3 6 9 8 7 4 5
A 3x3 matrix spirals to 1 2 3 6 9 8 7 4 5.
Example 2
Input
2 4 1 2 3 4 5 6 7 8
Output
1 2 3 4 8 7 6 5
A 2x4 matrix spirals to 1 2 3 4 8 7 6 5.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
3 3 1 2 3 4 5 6 7 8 9
Example 2 input
2 4 1 2 3 4 5 6 7 8