蛇形填数

来源:互联网 发布:sql笔试题及答案 编辑:程序博客网 时间:2024/05/16 10:44

在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 10using 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;}
0 0