Magical Magic Square
Title DescriptionMagic Square is a very magical n*n matrix: It is composed of digital three-way,......, n*n, and the sum of the numbers on each row, column, and two diagonal lines are the same.
When n is an odd number, we can construct a magic square by the following methods:
First write 1 in the middle of the first line.
Then, fill in each number of K (k=2,3,..., n*n) in the following way from small to large:
1. if (k−1) in the first row but not in the last column, the K is filled in the last row, (k−1) in the right column of the column;
2. if (k−1) in the last column but not in the first row, the K is filled in the first column, (k−1) on the row of the previous line;
3. if (k−1) in the last column of the first row, the K is filled directly below (k−1);
4. if (k−1) is neither in the first line nor in the last column, if the upper right of (k−1) is not filled, the k is filled in the upper right of (k−1), otherwise k is filled directly below (k−1).
Now given n please construct the magic square of N*n by the above method.
Input Format:
The input file has only one row and contains an integer n that is the size of the magic square.
output Format:
The output file contains n rows, n integers per line, that is, the magic side of the N*n constructed by the above method. Adjacent two integers are separated by a single space.
Input Sample:
3
Sample output:
8 1 6
3 5 7
4 9 2
#include <cstdio>inta[ +][ +],n;voidWorkintXintYintK//simulation, according to the title to write it good;{ inti=x,j=y,z=K; A[x][y]=K; if(k<n*N) { if(x==1&&y!=n) Work (n,y+1, K +1); Else if(x!=1&&y==n) Work (X-1,1, K +1); Else if(x==1&&y==n) Work (x+1, y,k+1); Else if(x!=1&&y!=n&&a[x-1][y+1]==0) Work (X-1, y+1, K +1); ElseWork (x+1, y,k+1); }} intMain () {scanf ("%d",&N); Work (1, (n+1)/2,1); for(intI=1; i<=n;i++){ for(intj=1; j<n;j++) printf ("%d", A[i][j]); printf ("%d\n", A[i][n]); } return 0;}
View Code
2015 day1.1 Magical Magic Square