24. 蛇形填数

题目:

在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 <= 8。

思路:

由题目可知,矩阵为方阵,因此用二维数组存储,同时将所有位置的值初始化为 0。

可将矩阵看成直角坐标系,并设每个数字坐标为(x , y),对应到二维数组的下标上。

扫描二维码关注公众号,回复: 8452431 查看本文章

假设当前位置为 “笔” 的位置,开始时,“笔” 在最右上角,坐标为(0 , n - 1) ,分析可得,“笔” 的移动轨迹为 先向下移动,再向左移动,再向上移动,再向右移动。整体上按照这4种方式,循环移动,必须注意,移动的先后次序不能颠倒。

举例来说,“笔” 一开始在最右上角,先填写数字,再向下移动,边移动边填写数字。

那么怎么判断该改变方向了呢?当向下移动时,先判断是否越过边界,再判断下一个位置是否被写过(没有被写过的格子值仍然是0, 被写过的格子值为数字),这样依次判断,直到 “笔”  应写的值超过格子数。

代码:

#include <iostream>
using namespace std;
const int MAXN = 20;
int matrix[MAXN][MAXN];

int main()
{
int n = 0;
cin >> n;
int x = 0, y = n - 1;
int pencil = 0;

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
matrix[i][j] = 0;
}
}

pencil = matrix[x][y] = 1;

while (pencil < n * n) {
while (x + 1 < n && !matrix[x + 1][y]) {
matrix[++x][y] = ++pencil;
}
while (y - 1 >= 0 && !matrix[x][y - 1]) {
matrix[x][--y] = ++pencil;
}
while (x - 1 >= 0 && !matrix[x - 1][y]) {
matrix[--x][y] = ++pencil;
}
while (y + 1 < n && !matrix[x][y + 1]) {
matrix[x][++y] = ++pencil;
}
}

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

猜你喜欢

转载自www.cnblogs.com/Hello-Nolan/p/12128045.html