蛇形填数。在n×n方阵里填入1,2,…,n×n,要求填成蛇形。
例如,n=4时方阵为:
10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
解决此题的一个重要原则就是先判断下一个要填的位置是否满足条件,再填数。不是发现了不能填再退回来。
代码如下:
#include
#include
#define MAXN 100
int matrix[MAXN][MAXN];
int main()
{
int n;
while(1 == scanf("%d", &n))
{
memset(matrix, 0, sizeof(matrix)); // 先将矩阵全部置为0
int x = 0, y = n - 1; // 从右上角开始填数
int ct = matrix[x][y] = 1; // 右上角第一个数填1
while(ct != n * n) // 填剩下的数,原则是先判断下一个要填的位置是否超出边界和是否为0,再填数
{
while(x + 1 < n && !matrix[x+1][y]) matrix[++x][y] = ++ct; // 由上倒下
while(y - 1 >= 0 && !matrix[x][y-1]) matrix[x][--y] = ++ct; // 由右到左
while(x - 1 >= 0 && !matrix[x-1][y]) matrix[--x][y] = ++ct; // 由下到上
while(y + 1 < n && !matrix[x][y+1]) matrix[x][++y] = ++ct; // 由左到右
}
for(x = 0; x < n; ++x) // 输出填好的矩阵
{
for(y = 0; y < n; ++y)
printf("%3d ", matrix[x][y]);
putchar('\n');
}
}
return 0;
}