zjut1005 做幻方
此题是求解奇幻方
记:关键是确定下一个数填的位置,规律是:1以后的每一个数只能填在它所在位置的下一行的下一列(记为A),如果A已经有数,就把下一个数填在当前这个数的上面(即与这个数同一列的上一个位置)
#include#include #define nmax 101 int num[nmax][nmax]; int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif int n, nn, i, j, k; while (~scanf("%d", &n) && n) { memset(num, 0, sizeof(num)); i = n - 1, j = n / 2, num[i][j] = 1; for (k = 2, nn = n * n; k <= nn; k++) { if (!num[(i + 1) % n][(j + 1) % n]) { i = (i + 1) % n, j = (j + 1) % n; } else { i = (i - 1 + n) % n; } num[i][j] = k; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%3d", num[i][j]); } printf("\n"); } printf("\n"); } return 0; }
/* * hdu3927.c * * Created on: 2011-9-22 * Author: bjfuwangzhu */ #include#define nmax 201 int num[nmax][nmax]; void solve(int n) { int i, j, k; for (i = 0, k = 1; i < n; i++) { for (j = 0; j < n - 1; j++) { num[i][j] = k, k++; } } for (i = 0; i < n; i++) { num[i][n - 1] = k, k++; } } int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif int t, k, i, j, n; while (~scanf("%d", &t)) { for (k = 1; k <= t; k++) { scanf("%d", &n); solve(n); printf("Case #%d:\n", k); for (i = 0; i < n; i++) { printf("%d", num[i][0]); for (j = 1; j < n; j++) { printf(" %d", num[i][j]); } printf("\n"); } } } return 0; }