Magic 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 method: 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 not in the first line, but also in the last column, if (K-1) is not filled at the top right, then K is filled in (K-1) in the upper right, otherwise L will be filled in (K-1) directly below.
Now given N, please construct n*n Magic Square according to the above method.
Input:
A row that contains a positive integer N, which is the size of the magic square.
Output:
Contains n rows, n integers per row, that is, the magic side of the N*n constructed by the above method, separated by a single space between two integers.
Input Example:
3
Output Example:
8 1 6
3 5 7
4 9 2
Data range: For all data, 1 <= n <= 39 and N is odd.
Very simple problem, simple simulation on the past ...
1#include <iostream>2 using namespacestd;3 intn,x,y;4 intmp[ $][ $];5 intMain ()6 {7Cin>>N;8x=1, Y= (n+1)/2;9mp[x][y]=1;Ten for(intI=2; i<=n*n;i++) One { A if(x==1&&y!=n) {x=n;y++;} - Else if(x!=1&&y==n) {x--;y=1;} - Else if(x==1&&y==n) x + +; the Else if(!mp[x-1][y+1]) {x--;y++;} - ElseX + +; -mp[x][y]=i; - } + for(intI=1; i<=n;i++) - { +cout<<mp[i][1]; A for(intj=2; j<=n;j++) printf ("%d", Mp[i][j]); atprintf"\ n"); - } - //System ("Pause>nul"); - return 0; -}
C + + answer
Brush over a question of the NOIP201505 magical magic Square