题目简介
输出蛇形图案,如:
1 2 3
8 9 4
7 6 5
说明
直接模拟,用控制方向的常量数组简化程序。
#include <stdio.h>
#include <stdbool.h>
#include <memory.h>
int n, x, y, num[11][11];
bool inside(int x, int y)
{
if (1 <= x && x <= n && 1 <= y && y <= n && num[x][y] == 0) return 1;
return 0;
}
int main()
{
int cas, i, j, t;
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
scanf("%d", &cas);
for (t = 0; t < cas; ++t){
scanf("%d", &n);
memset(num, 0, sizeof(num));
int now = 0, dir = 0;
x = 1;y = 1;
for (i = 1; i <= n * n; ++i){
num[x][y] = ++now;
if (now == n * n) break;
int x1 = x + dx[dir], y1 = y + dy[dir];
while (!inside(x1, y1)){
dir = (dir + 1) % 4;
x1 = x + dx[dir];
y1 = y + dy[dir];
}
x = x1; y = y1;
}
printf("case #%d:\n", t);
for (i = 1; i <= n; ++i){
printf("%d", num[i][1]);
for (j = 2; j <= n; ++j) printf(" %d", num[i][j]);
printf("\n");
}
}
return 0;
}