http://noi.openjudge.cn/ch0108/22/
-
Total time limit:
-
1000ms
-
Memory Limit:
-
65535kB
-
Describe
-
Magic Square is a very magical n*n matrix, it's each row, each column and the diagonal, plus the number is the same.
We can construct a magic square by the following methods. (Number of orders is odd)
1. The first digit is written in the middle of the first line
2. The next number is written in the upper right of the previous number:
A. If the number is in the first row, the next number is written in the last row, and the number of columns is the right column of the number
B. If the number is in the last column, the next number is written in the first column and the row number is the previous row of the number
C. If the number is in the upper-right corner, or there is a number at the top right of the number, the next digit is written below the number
-
Input
-
A number N (N<=20)
-
Output
-
The magic square of 2n-1 * 2n-1 constructed by the method
-
Sample input
-
3
-
Sample output
-
17 24 1 8 1523 5 7 14 164 6 13 20 2210 12 19 21 311 18 25 2 9
Analysis: According to the meaning of the topic, if a[i][j]=t, then the next to fill in the coordinates of the t+1 first consideration is x=i-1,y=j+1, but if i==0&&j==2*n-1 or a[x][y] has been occupied, should be placed in a[i][ J], just below.
So the code is:
1#include <stdio.h>2#include <stdlib.h>3 intMainintargcChar*argv[])4 {5 intn,i,j,t;6 int**A;7 LongNn,len;8 intx, y;9 Tenscanf"%d",&n); Onelen=2*n-1; AA= (int**)malloc(sizeof(int*)*len); - for(i=0; i<len;i++) -A[i]= (int*)malloc(sizeof(int)*len); the - for(i=0; i<len;i++) - for(j=0; j<len;j++) a[i][j]=0; - +I=0; -J= (n2-1)/2; +t=1; Aa[i][j]=T; atnn=len*Len; - while(t<nn) - { -t++; -x= (I-1+len)%Len; -Y= (j+1)%Len; in if(i==0&&j==len| | a[x][y]!=0) - { tox=i+1; +y=J; - } thea[x][y]=T; *I=x; $j=y;Panax Notoginseng } - the for(i=0; i<len;i++) + { A for(j=0; j<len;j++) the { +printf"%d", A[i][j]); - } $printf"\ n"); $ } - return 0; -}
The amount should actually write free () to release the memory, a little lazy, not written. Seems to be able to pass OJ's check O (∩_∩) o
Magical Magic Square is enough to create odd-order magic squares