一道有趣的编程题目: 蛇形填数

编写程序,在 N*N 的方阵里填入 1, 2, 3, …, N2,要求填成蛇形。例如,当 N=4 时,方阵为:

+----+----+----+---+
| 10 | 11 | 12 | 1 |
+----+----+----+---+
| 9  | 16 | 13 | 2 |
+----+----+----+---+
| 8  | 15 | 14 | 3 |
+----+----+----+---+
| 7  | 6  | 5  | 4 |
+----+----+----+---+

注意:方阵中的 +, -, | 和空格只为便于判断规律,不必严格输出,N≤8。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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;
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Site built with Hugo, hosted by Firebase.
Theme Stack designed by Jimmy.