EOJ 2983 蛇行图案

来源:互联网 发布:linux sip服务器 编辑:程序博客网 时间:2024/04/30 11:38

题目简介


输出蛇形图案,如:
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;}
原创粉丝点击