魔方矩阵的一般定义:将自然数 1 到 N^2, 排列 N 行 N 列的方阵,使每行、每列及两条主对角线上的 N 个数的和都等于N (N^2+1)/2,这样的方阵称为 N 阶幻方。
#include
using namespace std;
int count_dig(int n)//计算整数的位数,因为15的平方才225,所以最多3位
{
for(int i = 100, j = 3; i >=1 ; i /= 10, j--)
{
if(n / i >= 1)
return j;
}
}
int main()
{
int n;
int matrix[15][15];
bool first = true;
while(cin >> n)
{
if(!first)
cout << endl;
else first = false;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
matrix[i][j] = 0;//清零
int x = 0, y = n / 2;
matrix[x][y] = 1;
int next = 2;
int max = n * n;
while(next <= max)
{
int tmp_x = x - 1;//往右上角走
int tmp_y = y + 1;
if(tmp_x < 0)
tmp_x = tmp_x + n;//超出边界则会绕
if(tmp_y > n - 1)
tmp_y = tmp_y - n;
if(matrix[tmp_x][tmp_y] != 0 || (x == 0 && y == n - 1))//若右上角位置有数或前一个数位置是最右上角,则下一个数填在前一个数下面
x++;
else
{
x = tmp_x;
y = tmp_y;
}
matrix[x][y] = next++;
}
int length = count_dig(n * n);
cout << "n=" << n << ',' << " sum=" << (1 + n * n) * n / 2 << endl;
//输出矩阵
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << ' ';
for(int space = 0; space < length - count_dig(matrix[i][j]); space++)
cout << ' ';
cout << matrix[i][j];
}
cout << endl;
}
}
}
题目:
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square has only an odd number
N of rows and columns. For this problem you could expect the values
to be
3N15 .
A Magic Square is created by integer numbers in the range from 1 to
N2 , with a peculiar property, the ``sum of the numbers" in each row, column and diagonal is the same value.
For example the case for
n = 3 is:
M. Square Rows Columns Diagonals
8 1 6 8+1+6 = 15 8+3+4 = 15 8+5+2 = 15
3 5 7 3+5+7 = 15 1+5+9 = 15 4+5+6 = 15
4 9 2 4+9+2 = 15 6+7+2 = 15
Input
A file with several lines, each line has the value of
n .
Output
For each input line, print
N and the sum in the first line, followed by the magic square. To see a nice looking square, take into account the maximum length in characters of
N2 and
print each number with the maximum length preceded by one space or blank character. Print one line between squares.
Sample Input
3
5
Sample Output
n=3, sum=15
8 1 6
3 5 7
4 9 2
n=5, sum=65
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