幻方
幻方是一个方阵,其阶数为奇数,每行、每列和每条对角线的元素之和都相同。

每行、每列或每条对角线的总和可以使用此公式计算:n(n²+1)/2
以下是构造幻方的规则:
- 我们将从矩阵第一行的中间列开始,并始终移动到左上角放置下一个数字。
- 如果行超出范围或行不在矩阵中,则将列更改为最左列,并将数字放在矩阵的最后一行,然后再次移动到左上角。
- 如果列超出范围或列不在矩阵中,则将行更改为最顶行,并将数字放在该矩阵的最后一列,然后再次移动到左上角。
- 当左上角不为空或行和列都超出范围时,则将数字放在最后放置数字的底部。
输入和输出
Input: The order of the matrix 5 Output: 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11
算法
createSquare(mat, r, c)
输入:矩阵。
输出:行和列。
Begin count := 1 fill all elements in mat to 0 range := r * c i := 0 j := c/2 mat[i, j] := count //center of top row while count < range, do increase count by 1 if both i and j crosses the matrix range, then increase i by 1 else if only i crosses the matrix range, then i := c – 1 decrease j by 1 else if only j crosses the matrix range, then j := c – 1 decrease i by 1 else if i and j are in the matrix and element in (i, j) ≠ 0, then increase i by 1 else decrease i and j by 1 mat[i, j] := count done display the matrix mat End
示例
#include<iostream>
#include<iomanip>
using namespace std;
void createSquare(int **array, int r, int c) {
int i, j, count = 1, range;
for(i = 0; i<r; i++)
for(j = 0; j<c; j++)
array[i][j] = 0; //initialize all elements with 0
range = r*c;
i = 0;
j = c/2;
array[i][j] = count;
while(count < range) {
count++;
if((i-1) < 0 && (j-1) < 0) //when both row and column crosses the range
i++;
else if((i-1) <0) { //when only row crosses range, set i to last row, and decrease j
i = r-1;
j--;
}else if((j-1) < 0) { //when only col crosses range, set j to last column, and decrease i
j = c-1;
i--;
}else if(array[i-1][j-1] != 0) //when diagonal element is not empty, go to next row
i++;
else{
i--;
j--;
}
array[i][j] = count;
}
// Printing the square
for(i = 0; i<r; i++) {
for(j = 0; j<c; j++)
cout <<setw(3) << array[i][j];
cout << endl;
}
}
main() {
int** matrix;
int row, col;
cout << "Enter the order(odd) of square matrix :";
cin >> row;
col = row;
matrix = new int*[row];
for(int i = 0; i<row; i++) {
matrix[i] = new int[col];
}
createSquare(matrix, row, col);
}输出
Enter the order(odd) of square matrix :5 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP