在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

方阵中空格只为便于判断规律,不必严格输出,n≤8.

#include<iostream>
#include<iomanip>
#include<string.h>
#define maxn 10
using namespace std;
int a[maxn][maxn];
int main() {
int n,x,y,tot = 1;
cin >> n;
memset(a, 0, sizeof(a));//方阵置0方便判断
a[x = 0][y = n – 1] = 1;
while (tot < n*n){

//&&是短路运算符,即若x+1<n为false,将不会计算a[x+1][y] == 0,无需考虑越界的问题
while (x + 1 < n && a[x + 1][y] == 0) a[++x][y] = ++tot;
while (y – 1 >= 0 && a[x][y – 1] == 0) a[x][–y] = ++tot;
while (x – 1 >= 0 && a[x – 1][y] == 0) a[–x][y] = ++tot;
while (y + 1 < n && a[x][y + 1] == 0) a[x][++y] = ++tot;
}
for (int i = 0; i < n; i++) {
for (int k = 0; k < n; k++)
cout <<setw(3)<< a[i][k];
cout << endl;
}
system(“pause”);
return 0;
}