本文主要是介绍输出模魔方矩阵,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
魔方矩阵的一般定义:将自然数 1 到 N^2, 排列 N 行 N 列的方阵,使每行、每列及两条主对角线上的 N 个数的和都等于N (N^2+1)/2,这样的方阵称为 N 阶幻方。
#include<iostream>
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=158 1 63 5 74 9 2n=5, sum=6517 24 1 8 1523 5 7 14 164 6 13 20 2210 12 19 21 311 18 25 2 9
这篇关于输出模魔方矩阵的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!