• 蛇形填数


    算是比较简单吧,但觉得代码很优美,遂写下

    输入N,显示效果如下:

    学到:1.循环的安排形式  2.预判(试探),即先看看下个位置是否越界,是否填过,先看看,而不是先跳到那位置再看行不行,因为后悔就麻烦了!

    #include <iostream>
    #include <cstring>
    
    #define N 4
    int A[N][N];
    
    int main(void)
    {
        memset(A,0,sizeof(A));
    
        int total=1,x=0,y=N-1;
        A[x][y]=total;
    
        while (total<N*N)   //total为刚刚填好的格子里面的值,所以当total=N*N时,全部填好
        {
            while ((x+1<N)&&(A[x+1][y]==0))  //试探,下一个没有超出边界并且下一个没有填写过
            {
                x++,total++;  //跳到下一个,并且确定那里面的值
                A[x][y]=total;   //填值
            }  //这个结束后,坐标在最后填的那个格子里面,且total的值是那个格子里面的值
            while ((y-1>=0)&&(A[x][y-1]==0))
            {
                y--,total++;
                A[x][y]=total;
            }
            while ((x-1>=0)&&(A[x-1][y]==0))
            {
                x--,total++;
                A[x][y]=total;
            }
            while ((y+1<N)&&(A[x][y+1]==0))
            {
                y++,total++;
                A[x][y]=total;
            }
        }
    
        using std::endl;
        using std::cin;
        using std::cout;
        using std::ios_base;
        cout.setf(ios_base::left,ios_base::adjustfield);  //左对齐
    
        for (int i=0;i<N;i++)
        {
            for (int j=0;j<N;j++)
            {
                cout.width(3);   //显示宽度,只影响一个......
                cout<<A[i][j]<<" ";
            }
            cout<<endl;
        }
    
        cin.get();
        return 0;
    }
    View Code
  • 相关阅读:
    [转]<UNIX编程艺术>之精华文字
    2012年学习小结
    重试逻辑代码
    《构建高性能web站点》读书点滴
    mysql体系结构
    设计memcache的部署结构
    一般性hash算法c#版
    Flex带进度条的多文件上传(基于Servlet)
    C++11中值得关注的几大变化
    优化网站响应时间tomcat添加gzip
  • 原文地址:https://www.cnblogs.com/jiayith/p/3462729.html
Copyright © 2020-2023  润新知