Spiral order is an order especially used in 2-D Matrices or 2 dimensional matrices in which we have both rows and columns. In spiral order we print the matrix in a spiral form such as shown in the below figure.
As shown in the above figure we start printing the matrix from 1st row then move to the last column and then print the last row and then to the first column such as drawing a boundary to the inner sub-matrix then we move on to the inner sub-matrix until the whole matrix isn't printed.
Let us assume that we have given a matrix of size n*m as input that is having n rows and m columns .In order Algorithm :1.to print the spiral order of the matrix we use 4 variables or we require 4 variables.
1st variable which points the element where the row order has been started . row_start=0 since elements in the array start from index:0.
2nd variable which points the element where the row order has been ended. row_end=0 since elements in the array start from index:0 and ends at index:n-1.
3rd variable which points the element from where the column order has been started. column_start=0.
4th variable which points the element where the column order has been ended. column_end=0.
here we have 4 traversals for every boundary or for every spiral traversal that is from row_start to column_start , column_start to row_end ,row_end to column_end ,column_end to row_start.
2. First of all, we will traverse in the row row_start from column_start
to column_end and we will increase the row_start with 1 as we have
traversed the starting row.
3. Then we will traverse in the column column_end from row_start to
row_end and decrease the column_end by 1.
4. Then we will traverse in the row row_end from column_end to
column_start and decrease the row_end by 1.
5. Then we will traverse in the column column_start from row_end to
row_start and increase the column_start by 1.
6. We will do the above steps from 2 to 5 until row_start <= row_end
and column_start <= column_end.
using namespace std;
cout<<"enter the size of the 2-d array";
//reading the elements into the array
//spiral order printing
enter the size of the 2-d array 4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10