• 09-语言入门-09-蛇形填数


     
    描述
    在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
    10 11 12 1
    9 16 13 2
    8 15 14 3
    7 6 5 4

    输入
    直接输入方陈的维数,即n的值。(n<=100)

    输出
    输出结果是蛇形方阵。

    样例输入
    3

    样例输出
    7 8 1
    6 9 2
    5 4 3
     
    #include <stdio.h>
    #include <stdlib.h>

    static void setArr(int **arr,int readNum);
    static void printArr(int **arr,int num);

    int main()
    {
         int readNum = 0;
         scanf("%d",&readNum);
         getchar();
        
         int **arr = (int**)malloc(sizeof(int*)*readNum);
         int rowIndex = 0;
         for(;rowIndex < readNum;++rowIndex)
         {
              arr[rowIndex] = (int*)malloc(sizeof(int)*readNum);
         }
        
         setArr(arr,readNum);
         printArr(arr,readNum);
             
         rowIndex = 0;
         for(;rowIndex < readNum;++rowIndex)
         {
              free(arr[rowIndex]);
         }
         free(arr);
        
        
         return 0;
    }

    static void setArr(int **arr,int readNum)
    {
         int i=0;
         int flag = readNum;
         int colIndex = readNum-1;
         int rowIndex = 0;
         int maxNum = readNum*readNum;
         while(i<maxNum) //如果是偶数,则最大一个值在上侧执行完毕后就结束了
         {
              colIndex = flag-1;
             
              if(i == maxNum-1) //如果是奇数方阵,则最后一个数是最后一个最大值,特殊处理后结束
              {
                   arr[rowIndex][colIndex] = ++i;
                   break;
              }
             
              //右侧,行+,列不变
              for(;rowIndex<flag-1 && i<=maxNum;++rowIndex)
              {
                   arr[rowIndex][colIndex] = ++i;
              }
             
              //下侧,行不变 列-
              for(;colIndex>readNum-flag && i<=maxNum;--colIndex)
              {
                   arr[rowIndex][colIndex] = ++i;
              }
             
              //左侧,行-,列不变
              for(;rowIndex>readNum-flag && i<=maxNum;--rowIndex)
              {
                   arr[rowIndex][colIndex] = ++i;
              }
             
              //上侧,行不变,列++
              for(;colIndex<flag-1 && i<=maxNum;++colIndex)
              {
                   arr[rowIndex][colIndex] = ++i;
              }
             
              --flag;
              ++rowIndex;
         }
    }

    static void printArr(int **arr,int num)
    {
         int     rowIndex = 0;
         for(;rowIndex<num;++rowIndex)
         {
              int colIndex = 0;
              for(;colIndex < num;++colIndex)
              {
                   printf("%d ",arr[rowIndex][colIndex]);
              }
              printf(" ");
         }
    }
  • 相关阅读:
    Hackerrank--Emma and sum of products (FFT)
    Hdu 1402 (FFT)
    Hackerrank--Divisibility of Power(Math)
    Hackerrank--Stock Maximize(DP Practice)
    Codeforces 455B
    vim 简明教程(转自飘过的小牛)
    ACdream 1007 (快速幂)
    编写可维护的JS 02
    编写可维护的JS 01
    图片加载-从模糊到清晰
  • 原文地址:https://www.cnblogs.com/sharpfeng/p/5141207.html
Copyright © 2020-2023  润新知