题目来自刘汝佳编著的《算法竞赛入门经典(第二版)》
题目描述:
在 n*n 方阵中填入 1, 2, 3, ..., n*n 要求填成蛇形。 例如, n = 4 时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
我的代码(C++):
#include<iostream> using namespace std; int main(){ int n, i, j, m, time, t; int a[20][20]; cin >> n; m = 1; i = 0; j = n-1; time = n*n; t = n; while (m <= time) { while (i <= n - 1) { a[i][j] = m; m++; i++; } i--; j--; while (j >= t-n) { a[i][j] = m; m++; j--; } j++; i--; while (i >= t-n) { a[i][j] = m; m++; i--; } i++; n--; j++; while (j <= n - 1) { a[i][j] = m; m++; j++; } j--; i++; } for (i = 0; i < t; i++) { for (j = 0; j < t; j++) { cout << a[i][j] << " "; if (j == t - 1) cout << endl; } } return 0; }
答案的代码(C):
#include<stdio.h> #include<string.h> #define maxn 20 int a[maxn][maxn]; int main() { int n, x, y, tot = 0; scanf("%d", &n); memset(a, 0, sizeof(a)); tot = a[x = 0][y = n - 1] = 1; while (tot < n*n); { while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++tot; while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++tot; while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++tot; while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++tot; } for (x = 0; x < n; x++) { for (y = 0; y < n; y++) printf("%3d", a[x][y]); printf(" "); } return 0; }
如果哪位大神有更加厉害的算法,请不要吝啬哦~o(* ̄▽ ̄*)ブ