The so-called "Spiral Square", refers to any given n, the number of 1 to n*n from the upper left corner of the 1th lattice, according to the clockwise spiral direction in order to fill in the NxN square. The subject requires the construction of such a spiral phalanx.
Input format:
The input gives a positive integer n (<10) in a row.
Output format:
The spiral phalanx of the output nxn. n digits per line, 3 bits per digit.
Input Sample:
5
Sample output:
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 813 12 11) 10 9
#include <stdio.h> #define SIZE int main () { int a[size][size]={0}; int N; scanf ("%d", &n); increment int dx[]={0,1,0,-1} for each edge subscript on X, y ; int dy[]={1,0,-1,0}; int x=0,y=0,nx,ny,i,k=0; K is used to denote the side, k=0,1,2,3 respectively represents upper, right, bottom, left for (i=0;i<n*n;i++) { a[x][y]=i+1; NX=X+DX[K]; Position of next coordinate ny=y+dy[k]; if (nx<0 | | nx==n | | ny<0 | | ny==n | | a[nx][ny]!=0)//subscript out of bounds or subscript has been assigned, change direction { k= (k+1)%4; NX=X+DX[K]; NY=Y+DY[K]; } X=nx; Y=ny; } Int J; for (i=0;i<n;i++) { for (j=0;j<n;j++) { printf ("%3d", A[i][j]); } printf ("\ n"); } return 0;}
Array-13. Spiral Phalanx (20)