/*
Initialise the center element of the matrix with 1 and then assign all other cells in spiral order.
21 22 23 24 25
26 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
*/
// this will work only for odd number of rows and columns square matrix as in even rows and columns square //matrix there is no center element.
#include<iostream.h>
#include<conio.h>
const int rowcol=5;
int matrix[rowcol][rowcol];
void spiralinvert(int row,int col)
{
int count=2;
int cstart=col/2,cend=cstart+1;
int rstart=row/2,rend=rstart+1;
int n=row*col;
matrix[cstart][rstart]=1;
cout<<"spiral starts"<<endl;
while(1)
{
for(int i=cstart+1;i<=cend;i++,count++)
matrix[rstart][i]=count;
cstart--;
if(count>=n)
break;
for(int j=rstart+1;j<=rend;j++,count++)
matrix[j][cend]=count;
rstart--;
if(count>=n)
break;
for(int k=cend-1;k>=cstart;k--,count++)
matrix[rend][k]=count;
cend++;
if(count>=n)
break;
for(int l=rend-1;l>=rstart;l--,count++)
matrix[l][cstart]=count;
rend++;
if(count>=n)
break;
}
cout<<"spiral ends"<<endl;
}
void display(int row,int col)
{
for(int i=0;i<row;i++)
{
cout<<"\n";
for(int j=0;j<col;j++)
cout<<"\t"<<matrix[i][j];
}
}
int main()
{
spiralinvert(rowcol,rowcol);
display(rowcol,rowcol);
getch();
return 0;
}