4347: GESP C++四级样题_4填幻方
内存限制:128 MB
时间限制:1.000 S
评测方式:文本比较
命题人:
提交:1
解决:1
题目描述
样例输入 复制
3
样例输出 复制
8 1 6
3 5 7
4 9 2
提示
#include<bits/stdc++.h> using namespace std; int cube[21][21]; int main() { int n = 0; cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cube[i][j] = 0; // 清空正方形图表 int x = 0, y = n / 2; cube[x][y] = 1; // 第 1 步,第一行正中填写 1 for (int d = 2; d <= n * n; d++) { int nx = (x + n - 1) % n; int ny = (y + 1) % n; // 第 2 步,向右上移动一格 if (cube[nx][ny] != 0) { nx = (x + 1) % n; // 第 3 步,如果第 2 步失败,向下移动一格 ny = y; } cube[nx][ny] = d; // 填写下一个数字 x = nx; y = ny; } for (int i = 0; i < n; i++) { // 输出幻方 cout << cube[i][0]; for (int j = 1; j < n; j++) cout << " " << cube[i][j]; cout << endl; } return 0; }