Home > Back-end >  Title description is given a number N, the use of these number 1 to N ^ 2 in a N * N number of squar
Title description is given a number N, the use of these number 1 to N ^ 2 in a N * N number of squar

Time:12-01

Great god help, o this how to do,

CodePudding user response:

Output spiral square?

CodePudding user response:

Title is how the output of the square?

CodePudding user response:

Looks like a spiral phalanx
The idea is simple
Such as 5 * 5 square, from two-dimensional array (0, 0), according to the upper left to the right (1, 2, 3, 4), the upper to the lower right,6,7,8 (5), the right to lower left (9,10,11,12), bottom left to the upper left (13,14,15,16) 4 direction, each direction first print n - 1=4 elements, and then come back to the starting point (end of the first lap)
The second round of rotation, fixed starting point for the two-dimensional array (1, 1), or by direction, each direction to print n - 1-2=2 elements (17, 18), (19, 20), (21, 22), (23, 24), and then come back to the starting point; Continue to the next round of rotation, the correct starting point and print elements in each direction, until the count to n * n
1, 2, 3, 4, 5
19 June 16 17 18
15 20 July 24 25
14 and 22 21 8
11 12 13 October 9

 int main () {
Int n, I, j, k, d, c, t, end;
Printf (" please enter an integer greater than 0: ");
The scanf (" % d ", & amp; n);
Int m=(int) * * * * malloc (sizeof (int *) * n);//dynamic application memory (two-dimensional array)
for (i=0; iM [I]=(int *) malloc (sizeof (int) * n);
}
End=n * n;
For (I=0, j=0, k=n - 1, d=0, c=1;; ) {//from starts at (0, 0), the direction of d=0 is from upper left to lower right, print k element in each direction, starting from 1
cFor (t=(k<=0? 1: k); T> 0 & amp; & C<=end; T -) {
If (d==0)//upper left to the upper right
M [I] [j++]=c + +;
Else if (d==1)//at the upper to the lower right
M [i++] [j]=c + +;
Else if (d==2)//right to lower left
M [I] [j -]=c + +;
The else//lower left to upper left
M [I -] [j]=c + +;
}
If (c> End) break;//count all the exit loop
D=(d + 1) % 4;//a total of four directions, through a direction to the next direction
If (d==0) {//back to the origin is revision to the starting point and the number of each direction of the print element
i++;
j++;
K -=2;//why - 2? Because reduce an element is a total of around each two elements (similarly in the direction of up and down)
}
}
for (i=0; iFor (j=0; JPrintf (" % 3 d, "m [I] [j]);
}
printf("\n");
[I] free (m);
}
Free (m);//release the memory
return 0;
}