Python Program to Print a Matrix in Spiral Order
Intermediate · Matrices
Spiral order reads a matrix from the outside in: along the top row, down the right column, back along the bottom row, up the left column, and then round again on the inner part. This program keeps four boundaries, top, bottom, left and right, and moves them inwards after each side is read.
Program
Matrix: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] Spiral order: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
How it works
top,bottom,leftandrightmark the edges of the part of the matrix not read yet.- Each pass of the
whileloop reads one ring: the top row, the right column, the bottom row backwards and the left column upwards. - After a side is read, its boundary moves one step inwards, so it is never read twice.
- The two
ifchecks stop a single leftover row or column from being read a second time, which matters for matrices that are not square, like this 3 x 4 one. - The loop ends when the boundaries cross, which means every entry has been read.
Other ways to write it
Peeling off the top row and turning the rest
Spiral order: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Taking the top row and turning what is left a quarter turn anticlockwise brings the next side to the top each time. It is short, but it rebuilds the grid on every step.
Filling a matrix in spiral order
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
The reverse task writes 1 to n x n into the cells along the spiral, turning right whenever the next cell is off the grid or already filled.
Try it yourself
Add a fourth row, [13, 14, 15, 16], and predict the spiral order before you run it.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises