《神奇的幻方》代码求助
  • 板块题目总版
  • 楼主L_Legend
  • 当前回复2
  • 已保存回复2
  • 发布时间2021/7/9 10:53
  • 上次更新2023/11/4 15:14:25
查看原帖
《神奇的幻方》代码求助
533879
L_Legend楼主2021/7/9 10:53
#include<bits/stdc++.h>
using namespace std;
int f[40][40];
int main() {
	int n;
	cin >> n;
	if (n == 1) {
		cout << "1" << endl;
		return 0;
	}
	int x = 1, y = (n + 1) / 2;
	for (int i = 1; i <= n * n; i++) {
		f[x][y] = i;
		if (x == 1 && y != n) {
			x = n;
			y += 1;
		} else if (x != 1 && y == n) {
			x -= 1;
			y = 1;
		} else if (x == 1 && y == n) {
			x = 1;
			y += 1;
		} else if (x != 1 && y != n) {
			if (f[x + 1][y + 1] == 0) {
				x -= 1;
				y += 1;
			} else {
				x = 1;
				y += 1;
			}
		}
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cout << f[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}
2021/7/9 10:53
加载中...