Print Matrix in Spiral Order

Given a MxN matrix, print matrix in spiral order.


For example,

Input:

[  1  2  3  4 5 ]
[ 16 17 18 19 6 ]
[ 15 24 25 20 7 ]
[ 14 23 22 21 8 ]
[ 13 12 11 10 9 ]

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25


The idea is to read elements from the given matrix one by one and print matrix in spiral order. To maintain the spiral order four loops are used, each for top, right, bottom and left corner of the matrix.

 
C++ implementation –
 

Download   Run Code

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

 
We can also achieve this easily with the help of recursion.
 
Recurvive C++ implementation –
 

Download   Run Code

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Time complexity of above solution is O(M*N).
Auxiliary space used by the program is O(1).

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz