zoukankan      html  css  js  c++  java
  • SDUSTOJ 1184

    题目

    Description
    将1~n*n填入一个n*n的矩阵中,并要求成为蛇形。蛇形即是从右上角开始向下,向左,向上,向右,循环填入数字。
    比如n=5时矩阵为:
    13 14 15 16 1
    12 23 24 17 2
    11 22 25 18 3
    10 21 20 19 4
    9 8 7 6 5
    Input
    输入有多行,每行为一个整数n(1<=n<=50),每组答案用空行隔开。
    Output
    输出一个n*n的矩阵,n行n列每个数字用一个空格隔开,不能有多余空格。
    Sample Input
    5
    Sample Output
    13 14 15 16 1
    12 23 24 17 2
    11 22 25 18 3
    10 21 20 19 4
    9 8 7 6 5

    思路

    紫书上讲过这个蛇形填数的题目

    从1开始依次填写。设“笔”的坐标为(x,y),则一开始x=0,y=n-1,即第0行,第n-1列(行列的范围是0~n-1,没有第n列)。“笔”的移动轨迹是:下,下,下,左,左,左,上,上,上,右,右,下,下,左,上。总之,先是下,到不能填为止,然后是左,接着是上,最后是右。“不能填”是指再走就出界(例如4→5),或者再走就要走到以前填过的格子(例如12→13)。如果把所有格子初始化为0,就能很方便地加以判

    AC代码

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define maxn 50+10
    
    int a[maxn][maxn];
    
    void putarray( int s[maxn][maxn], int n )
    {
        for( int i = 0; i < n; i++)
        {
            for( int j = 0; j < n; j++)
            {
                if( j != 0 )
                    printf(" ");
                printf("%d", a[i][j]);
            }
            puts("");
        }
    }
    
    int main()
    {
        int n, x, y, t = 0;
        int num = 0;
        while( ~scanf("%d", &n) )
        {
            if( ++num != 1 )
                puts("");
            memset(a, 0, sizeof(a));
            x = 0, y = n-1;
            t = a[x][y] = 1;
            while(t < n*n)
            {
                while(x + 1 < n && !a[x+1][y])
                    a[++x][y] = ++t;
                while(y - 1 >= 0 && !a[x][y-1])
                    a[x][--y] = ++t;
                while(x - 1 >= 0 && !a[x-1][y])
                    a[--x][y] = ++t;
                while(y + 1 < n && !a[x][y+1])
                    a[x][++y] = ++t;
            }
    
            putarray(a,n);
        }
        return 0;
    }
  • 相关阅读:
    linq 读取xml
    c# 定时器 自动执行
    如何在一个人输入框中只输入数字
    如何去掉滚动条,
    如何计算任意值之间的随机数呢
    【P2387】魔法森林(SPFA非正解)
    【Luogu】P3203弹飞绵羊(分块)
    【Luogu】P3396哈希冲突(根号算法)
    【Luogu】P2801教主的魔法(分块)
    【Luogu】P3155叶子的染色(树形DP)
  • 原文地址:https://www.cnblogs.com/JinxiSui/p/9740648.html
Copyright © 2011-2022 走看看