C语言 螺旋方阵解析(C language spiral square analysis)
C语言 螺旋方阵解析(C language spiral square analysis)
Three spiral square
Title: Input Height N, printf such pattern:
1, 2, 3, 4, 5
16, 17, 17, 18, 19, 6
15, 24, 25, 20, 7
14 23 22 21 8
13, 12, 11, 10, 9
The first solution is to use an arithmetic sequence to solve this problem.
Algorithm:
1, 2, 3, 4, 5
16, 17, 18, 19, 6
15, 24, 25, 20, 7
14 23 22 21 8
13, 12, 11, 10, 9
Define row I column j. It's stratified from the outside, one layer at a time. Definition r: (r BBB 0 = 1) the current loop is the first lap.
Definition N: graphic height
Definition l: current loop length l
L (1) = N - 1
L (r) = N - 2 * (r - 1) - 1
Set the top left corner of the current loop to start. Definition d: current row direction (top 0 on the right side of 1 and 2 to the left is 3)
Definition pl: current loop length (direction to small number)
Definition a: how many digits are there in the current loop
A (r) = l (r) = 4 * 4 * 2 * (N - (r - 1))
Tolerance for eight
Sum from the outermost circle to the current loop: s (r) = a (1) * r-r * (r - 1) / 2 * (-8)
Definition b: the first number in this circle
B (r) = s (r - 1) + 1
= a (1) * (r - 1) - (r - 1) * (r - 2) / 2 * (8) + 1
Start calculation:
R: r = min (I, N - j + 1, N - I + 1, j)
D: d is (I, N - j + 1, N - I + 1, j) corresponds to r, if r is the first value, then d is the first value...
Pl: p = (j - r, I - r, N - j + 1 - r, N - I + 1 - r) and r correspondence, such as r, such as the first value, it is the first value d...
Current value b + l * d + pl
Commented by Wang Rui
The program is as follows:
The main ()
{int I, j, r, l, b, d, pl, N.
Printf (" Input Height: "); / * input height * /
The scanf (" % d ", & N);
For (I = 1; I < = N i++)
{for (j = 1; j < = N; j + +) / * locates to row I, j column * /
{r = I; D = 0; Pl = j - r;
If (r > N - j + 1) {r = N - j + 1; D = 1; Pl = I - r; }
If (r > N - I + 1) {r = N - (I) + 1; D = 2; Pl = N - j + 1 - r; }
If (r > j) {r = j; D = 3; Pl = N - I + 1 - r; }
/ * find out the number of loops, side position, side positi