I have written code for scanning an N x M matrix in spiral order using a recursive function.
It uses 5 parameters - including 2 extra variables:
call
to keep track of the no. of current callcounter
to keep track of no. of elements already printed
Example:
For matrix:
1 2 3
4 5 6
7 8 9
For call = 0:
Output: 1 2 3 6 9 8 7 4 counter = 8
For call = 1:
Output: 5 counter = 9
Can the code be improved so that it uses fewer no. of variables and is more efficient?
#include <stdio.h>
#include <stdlib.h>
void spiralscan(int a[][20],int n,int m,int call,int counter)
{
int i,j;
if(counter>=n*m)
return;
//scan top
//if(m>call)
{ printf("\ntop\n");
for(j=call;j<m-call;j++)
{printf(" %d ",a[call][j]);
counter++;
}
}
if(counter>=n*m)
return;
//scan right
// if(n-call>0)
{ printf("\nright\n");
for(i=call+1;i<n-call;i++)
{printf(" %d ",a[i][m-call-1]);
counter++;
}
}
if(counter>=n*m)
return;
//scan bottom
// if(m-call>0)
{ printf("\nbottom\n");
for(j=m-2-call;j>=call;j--)
{printf(" %d ",a[n-1-call][j]);
counter++;
}
}
if(counter>=n*m)
return;
//scan left
// if(call<n/2)
{ printf("\nleft\n");
for(i=n-2-call;i>call;i--)
{printf(" %d ",a[i][call]);
counter++;
}
}
if(counter>=n*m)
return;
spiralscan(a,n,m,call+1,counter);
}
int main()
{
int n,m,i,j,a[20][20];
printf("\t\t\tSpiral Scanning\n\n");
printf("no. of rows : ");
scanf("%d",&n);
printf("\nno. of columns : ");
scanf("%d",&m);
printf("\nEnter matrix elements : \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
}
printf("\n\n\t\tScanning Spirally\n\n");
spiralscan(a,n,m,0,0);
return 0;
}