"Praveen" <rp**********@gmail.comwrote in message
news:24**********************************@k39g2000 hsf.googlegroups.com...
Hi,
I would like to know how to traverse an array spirally?
i.e if I have an array as follows
1 2 3 4
5 6 7 8
9 10 11 12
I want the output to be 1 2 3 4 8 12 11 10 9 5 6 7.
Please help
Interesting exercise. But not really specific to C except array bounds have
to start at 0.
This is my effort. Probably some clever logic needed but I found it easier
to use a map of 1s and 0s to indicate which array elements have been
visited.
Ints m and n have the array dims hardcoded. Dynamic bounds are a little more
involved.
BTW I'm new to C so if this is homework... don't rely on this!
Bart
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int m=8,n=6;
int x[n][m];
int map[n][m];
int i,j,k,c,l,count,total,dir;
k=1;
c=1;
l=1;
/* print array grid */
while (1)
{ printf("%3d",k);
++k;
++c;
if (c>m)
{
printf("\n");
c = 1;
++l;
if (l>n) break;
}
}
printf("\n");
/* Set up map of 1's for each array element */
k = 1;
for (j=0; j<n; ++j)
for (i=0; i<m; ++i)
{
x[j][i] = k++; /* the grid */
map[j][i] = 1; /* the map */
};
/* now search clockwise spiral */
i = 0;
j = 0;
dir = 'R'; /* One of 4 directions R D L U */
total = m*n;
count = 0;
while (1)
{/*w1"*/
printf(" %d",x[j][i]); /* output contents of this grid element */
map[j][i] = 0; /* mark as visited */
++count;
if (count==total) break;
while (1)
{/*w2*/
switch (dir)
{/*sw*/
case 'R':
if (i<(m-1) && map[j][i+1])
{++i;
goto endwhile; /* C can't use break out of 2 levels :-) */
}
else
dir = 'D';
break;
case 'D':
if (j<(n-1) && map[j+1][i])
{++j;
goto endwhile;
}
else
dir = 'L';
break;
case 'L':
if (i>0 && map[j][i-1])
{--i;
goto endwhile;
}
else
dir = 'U';
break;
case 'U':
if (j>0 && map[j-1][i])
{--j;
goto endwhile;
}
else
dir = 'R';
break;
}; /*sw*/
}; /*w2*/
endwhile:;
}; /*w1*/
printf("\n");
}