Magical Magic Square.
View Submit Statistics Questions
Total time limit: 1000ms memory limit: 65535kB
Describe
The Magic Square is a very magical n*n matrix, with each row, column and diagonal, the numbers combined are the same.
We can build a magic square in the following ways. (Order is odd)
1. The first number is written in the middle of the first line.
2. The next number is written on the top 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 column is the right column of that 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 if there is already a number on the upper right of the number, the next number is written below the number
Input
A number N (N<=20)
Output
Magic square of 2n-1 * 2n-1 constructed by means of the above method
Sample input
3
Sample output
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
OpenJudge-6 Magical Magic Square
#include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{
int a[40][40]={0};
int n,nc;
cin>>n;
int length;
Length =2*n-1;
NC = length*length;
int i,j;
int ipre,jpre;
for (i=0;i<nc;i++)
{
if (i==0)
{
ipre=0;
jpre=n-1;
a[ipre][jpre]=i+1;
Continue;
}
else if (ipre==0 && jpre!=length-1)
{
ipre=length-1;
jpre=jpre+1;
a[ipre][jpre]=i+1;
}
else if (Jpre = = Length-1 &&ipre!= 0)
{
ipre=ipre-1;
jpre=0;
a[ipre][jpre]=i+1;
}
else if ((Ipre = = 0&& jpre==length-1) | | a[ipre-1][jpre+1]!=0)
{
ipre=ipre+1;
Jpre=jpre;
a[ipre][jpre]=i+1;
}
else
{
ipre=ipre-1;
jpre=jpre+1;
A[ipre][jpre]=i+1
}
}
for (i=0;i<length;i++)
{for
(j=0;j<length;j++)
if (j==0)
cout<<a[i][j];
else
cout<< "" <<a[i][j];
cout<<endl;
}
return 0;
}