蛇形填数

  在 n×n 方阵里填入 1,2,...n×n, 要求填成蛇形(n<=8)。例如,n=4 时方阵为:

    10  11  12  1

    9  16  13  2

    8   15  14  3

    7   6    5  4

 

分析:使用二维数组,并使每次填入的坐标为(x,y),按照蛇形移动坐标即可

C++代码如下:

 1 #include<iostream>
 2 #include<string.h>
 3 #include<iomanip>
 4 using namespace std;
 5 #define maxn 10
 6 int a[maxn][maxn];
 7 int main() {
 8     int x, y, n, tot=1;
 9     cin >> n;
10     memset(a, 0, sizeof(a)); //将数组元素全部填充为0
11     a[x = 0][y = n - 1] = tot;
12     while (tot < n*n) {
13         while (x + 1 < n && !a[x+1][y]) a[++x][y] = ++tot;  //移动坐标并判断将要填入数值的元素是否已经填入其他非0数值
14         while (y - 1 >=0 && !a[x][y-1]) a[x][--y] = ++tot;
15         while (x - 1 >=0 && !a[x-1][y]) a[--x][y] = ++tot;
16         while (y + 1 < n && !a[x][y+1]) a[x][++y] = ++tot;
17     }
18     for (x = 0; x < n; x++) {
19         for (y = 0; y < n; y++)
20             cout <<setw(6)<< a[x][y];
21         cout << endl;    
22     }
23     return 0;
24 }
posted on 2018-06-24 17:23  Pink.Pig  阅读(297)  评论(0编辑  收藏  举报