Printing a matrix in spiral form is one of the most asked interview question of all times. In this problem we are given a matrix and we have print it in spiral manner. First we have to print the outer layer then we go inner layer and we keep doing it until we reach the core. This is the basic idea to solve this problem.
Lets assume we are given a 4x4 matrix .
Output : 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Explaination : As mentioned earlier first we print the outer layer
ie. 1 then 2 ,3 ,4 ,8 , 12 ,16, 15, 14, 13, 9 ,5
Once we are done with outer layer we will go inside and again print the outer layer for that inner matrix ie. 6 then 7 , 11 and 10
Output : 3 6 9 10 11 8 5 4 7
Time Complexity : O(R*C) ; where R is the total number of rows and C is total number of columns.