蛇形填数。在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个数字输入结束后,后面输入可以分组输入
int snake[9][9];
int main()
{
int n,i=1,m=0;
cin >> n;
int x = n - 1, y = 0;
memset(snake, 0, sizeof(snake));
for (; i < n; i++)
snake[y++][x] = i;
snake[y][x--] = i;//ok
while (n--)
{
m++;
if (!n)break;
if (m % 2 == 1)//如果n减少量m为奇数,执行左移x--和上移y--
{
for (int j = 1; j < n; j++)
snake[y][x--] = ++i;
snake[y--][x] = ++i;
for (int j = 1; j < n; j++)
snake[y--][x] =++ i;
snake[y][x++] = ++i;
}
if (m % 2 == 0)
{
for (int j = 1; j < n; j++)
snake[y][x++] =++ i;
snake[y++][x] =++ i;
for (int j = 1; j < n; j++)
snake[y++][x] =++ i;
snake[y][x--] = ++i;
}
}
for (int a = 0; a < m; a++)
{
for (int b = 0; b < m; b++)
cout << snake[a][b] << '\t';
cout << endl;
}
}
结果
不过这样写自加的部分很容易出错,且每组最后一个输入 还要通过另外一个语句
书上的思路是自主判断每组的输入
若下一个位置没有越界且为值0则可以继续输入,若不符合条件就需要 换方向输入下一组了
#define maxn 20
int a[maxn][maxn];
int main()
{
int n, x, y, tot = 0;
cin >> n;
memset(a, 0, sizeof(a));
tot = a[x = 0][y = n - 1] = 1;
while (tot < n * n)
{
while (x + 1 < n && !a[x + 1][y])
a[++x][y] = ++tot;
while (y - 1 >= 0 && !a[x][y - 1])
a[x][--y] = ++tot;
while (x - 1 >= 0 && !a[x - 1][y])
a[--x][y] = ++tot;
while (y + 1 < n && !a[x][y + 1])
a[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
cout << a[x][y]<<'\t';
}
cout << endl;
}
}