Printing a 2D matrix in spiral form is a popular interview problem that involves traversing the elements in a specific order. This article explains the problem, its solution, and a Python implementation. We’ll also provide test cases, algorithm breakdowns, and tips to understand and visualize this problem better.
Given a matrix of size M×NM \times N, print its elements in spiral order. The traversal begins from the top-left corner and moves as follows:
Matrix:
[123456789101112131415161718]\begin{bmatrix} 1 & 2 & 3 & 4 & 5 & 6 \\ 7 & 8 & 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 & 17 & 18 \end{bmatrix}
Output:
1,2,3,4,5,6,12,18,17,16,15,14,13,7,8,9,10,111, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11
top
, bottom
, left
, and right
.left
to right
across the top boundary.top
to bottom
along the right boundary.right
to left
across the bottom boundary.bottom
to top
along the left boundary.