构造幻方

54 阅读1分钟

郑大OJ1091做幻方

第一次提交时,幻方的顺序不对,就错了。只有按样例做出的幻方才能过此题。输出格式也后要求,PE展示错误了几次。

以下代码实现了la Loubere的构造幻方的方法。其中n为奇数,pic[][]是全局的变量

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int pic[33][33];
void solve(int n) {
	memset(pic, 0, sizeof(pic));
	int n2 = n * n;
	int x = n, y = (n + 1) >> 1;
	for (int i = 1; i <= n2; ++i) {
		pic[x][y] = i;
		if (x == n) {
			if (y == n)
				x--;
			else {
				x = 1;
				y++;
			}
		}
		else { //这里不能用else if
			if (y == n) {
				y = 1;
				x++;
			}
			else {
				if (pic[x + 1][y + 1] != 0)
					x--;
				else {
					x++;
					y++;
				}
			}
		}
	}
}
int main()
{
	int n;
	bool first = true;
	char presention[3][5] = {{"%1d"},{"%2d"}, {"%3d"}};
	while (~scanf("%d", &n) && n) {
		solve(n);
		if (first) 
			first = false;
		else puts("");
		int cur = (n < 10 ? 1 : 2);
		if (n == 1)
			cur = 0;
		for (int i = 1; i <= n; ++i) {
			printf(presention[cur], pic[i][1]);
			for (int j = 2; j <= n; ++j) {
				putchar(' ');
				printf(presention[cur], pic[i][j]);
			}
			puts("");			
		}		 
	}

	return 0;
}


另一种顺序的幻方。

int pic[33][33];
void solve(int n) {
	memset(pic, 0, sizeof(pic));
	int n2 = n * n;
	int x = 1, y = (n + 1) >> 1;
	for (int i = 1; i <= n2; ++i) {
		pic[x][y] = i;
		if (x == 1) {
			if (y == n)
				x++;
			else {
				x = n;
				y++;
			}
		}
		else { //这里不能用else if
			if (y == n) {
				y = 1;
				x--;
			}
			else {
				if (pic[x - 1][y + 1] != 0)
					x++;
				else {
					x--;
					y++;
				}
			}
		}
	}
}


\