#include <iostream>
#include <vector>
using namespace std;
//构建幻方
vector<vector<int>> buildMagicSquare(int N) {
vector<vector<int>> square(2 * N - 1, vector<int>(2 * N - 1, 0));
int num = 1;
int row = 0;
int col = N - 1;
while (num <= (2 * N - 1) * (2 * N - 1)) {
square[row][col] = num;
int nextRow = (row - 1 + 2 * N - 1) % (2 * N - 1);
int nextCol = (col + 1) % (2 * N - 1);
if (square[nextRow][nextCol] != 0) {
row = (row + 1) % (2 * N - 1);
}
else {
row = nextRow;
col = nextCol;
}
num++;
}
return square;
}
// 打印幻方
void printMagicSquare(const vector<vector<int>>& square) {
int N = (square.size() + 1) / 2;
for (int i = 0; i < square.size(); i++) {
for (int j = 0; j < square[i].size(); j++) {
cout << square[i][j] << " ";
}
cout << endl;
}
}
int main() {
int N;
cin >> N;
vector<vector<int>> square = buildMagicSquare(N);
printMagicSquare(square);
return 0;
}
03-06
07-09
2209
08-13
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交