山东科技大学OJ蛇形填阵

 蛇形填阵问题主要利用二维数组解决,但赋值是一大难题,只要掌握了这条“蛇”的运动方向就可以轻松搞定啦,这里用到了平常不常用的++shu操作,意思就是先用这个数在实行++操作。

            while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++shu;
            while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++shu;
            while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++shu;
            while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++shu;

第一行就是蛇从右上角向右下角运动时的赋值;

第二行就是蛇从右下角向左下角运动时的赋值;

第三行就是蛇从左下角向左上角运动时的赋值;

第四行就是蛇从左上角向右上角运动时的赋值;

。。。。。。。。。。。。。。。。。。。。

依次这样循环直到数达到了n*n就停止。

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

喏~~~代码来啦!!!!!

#include<stdio.h>
#include<string.h>
#define maxn 55
int main()
{
    int a[maxn][maxn];
    //freopen("output.txt","w",stdout);
    int n, x, y, shu = 0;
    int i,j,k;
    while(scanf("%d", &n)==1)
    {
        memset(a, 0, sizeof(a));
        a[x = 0][y = n - 1] = shu = 1;
        while (shu < n * n)
        {
            while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++shu;
            while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++shu;
            while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++shu;
            while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++shu;
        }
        for(i=0;i<n;i++)
        {
            printf("%d",a[i][0]);
            for(j=1;j<n;j++)
                printf(" %d",a[i][j]);
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}

希望大家多多关注,小鑫会很努力地写博客的,我在这给各位大爷跪下了     噗通~~~~~~!

猜你喜欢

转载自blog.csdn.net/weixin_43820496/article/details/85055504
今日推荐