蛇形填数

描述:在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12  1
  9 16 13  2
  8 15 14  3
  7  6    5  4

 

思路:若输入n=4,则矩阵中最大为4*4 = 16.   填数时,应该在最右上角位置开始,也就是第0行,第n-1列开始。列不变行向下到底端,  行不变列向左到边界,  列不变行向上到边界,  行不变列增加到已被赋值的数, 列不变行向下到已被赋值的数。。。。一直循环按此规律循环。。直到元素值比n*n大

下面代码外循环控制整体需要结束的条件,  4个内循环分别的功能是向下,向左,向上,向右,在具体循环的时候,每次都是先判断在执行,先试探下一个元素是否没有越边界或是否无值,才能继续向下,否则进入下一个while循环,变换方向。

 1 #include<iostream>    
 2 
 3 using namespace std;
 4 #define MAXN 10
 5 int a[MAXN][MAXN];
 6 int main()
 7 {
 8     int n, x, y, tot = 0;
 9     cin >> n;
10     x = 0;
11     y = n - 1;
12     tot=a[x][y] = 1;
13     while (tot < n*n) {
14         while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++tot;
15         while (y - 1 >= 0 && !a[x][y - 1])a[x][--y] = ++tot;
16         while (x - 1 >= 0 && !a[x - 1][y])a[--x][y] = ++tot;
17         while (y + 1 < n && !a[x][y + 1])a[x][++y] = ++tot;
18     }
19     for (x = 0; x < n; x++) {
20         for (y = 0; y < n; y++) {
21             printf("%3d", a[x][y]);
22         }
23         cout << endl;
24     }
25 
26     system("pause");
27 }

 

类似问题,蛇形矩阵

 

1 3 6 10 15

2 5 9 14

4 8 13

7 12

11

 

 1 #include<iostream>    
 2 
 3 using namespace std;
 4 #define MAXN 10
 5 int a[MAXN][MAXN];
 6 int main()
 7 {
 8     int n;
 9     int i = 1;
10     int x = 1, y = 0;
11     int c = 1;
12     a[0][0] = 1;
13     cin >> n;
14 
15     while (i < n) {
16         x = i;
17         y = 0;
18         while (y <= i) {
19             a[x--][y++] = ++c;
20         }
21         i++;
22     }
23     for (i = 0; i < n; i++) {
24         for (int j = 0; j < n - i; j++)
25             printf("%5d", a[i][j]);
26         cout << endl;
27     }
28 
29     system("pause");
30 }

 

参考 https://blog.csdn.net/qq_36238595/article/details/53537672

posted @ 2018-09-02 16:34  朴者  阅读(223)  评论(0编辑  收藏  举报