zoukankan      html  css  js  c++  java
  • 数组-13. 螺旋方阵(20)

    所谓“螺旋方阵”,是指对任意给定的N,将1到N*N的数字从左上角第1个格子开始,按顺时针螺旋方向顺序填入NxN的方阵里。本题要求构造这样的螺旋方阵。

    输入格式:

    输入在一行中给出一个正整数N(<10)。

    输出格式:

    输出NxN的螺旋方阵。每行N个数字,每个数字占3位。

    输入样例:

    5
    

    输出样例:

      1  2  3  4  5
     16 17 18 19  6
     15 24 25 20  7
     14 23 22 21  8
     13 12 11 10  9
    
     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <math.h>
     4 #include <string.h>
     5 #include <stdlib.h>
     6 
     7 using namespace::std; 
     8 int print(int a[10][10],int n)
     9 {
    10     for(int i=0;i<n;i++)
    11     {
    12     for(int j=0;j<n;j++)
    13     {
    14         printf("%3d",a[i][j]);
    15     //    if(j!=n-1)
    16     //    printf(" ");
    17     } 
    18     printf("
    ");
    19     } 
    20     return 0;
    21 }
    22 int main(){
    23       int n;
    24       scanf("%d",&n);
    25         int round=ceil(n/2.0);
    26       int count=0;
    27       int a[10][10]={0};
    28       for(int i=0;i<round;i++)
    29       {
    30           //画方阵,第i+1轮,上 
    31           if(count==n*n-1){
    32               a[round-1][round-1]=n*n;
    33               print(a,n);
    34               return 0;
    35           }
    36         for(int j=0;j<n-2*i-1;j++)
    37         {
    38             count++;
    39             a[i][i+j]=count; 
    40         //    print(a,n);
    41             if(count==n*n){
    42             print(a,n);
    43             return 0;  
    44         }
    45         }
    46         //
    47         for(int j=0;j<n-2*i-1;j++)
    48         {
    49             count++;
    50             a[i+j][n-i-1]=count;
    51         //    print(a,n);
    52         }
    53         //
    54         for(int j=0;j<n-2*i-1;j++)
    55         {
    56             count++;
    57             a[n-i-1][n-i-1-j]=count; 
    58         //    print(a,n);
    59         }
    60         //
    61         for(int j=0;j<n-2*i-1;j++)
    62         {
    63             count++;
    64             a[n-i-1-j][i]=count; 
    65         //    print(a,n);
    66         }
    67         if(count==n*n){
    68              print(a,n);
    69              return 0; 
    70         }   
    71       }
    72       
    73      
    74       return 0;
    75 }
  • 相关阅读:
    Longest Common Substring
    未完成 Anagrams
    strStr
    vim的学习笔记
    Compare Strings
    Two Strings Are Anagrams
    KMP算法
    [ 力扣活动0314 ] 300. 最长上升子序列
    [ 力扣活动0317 ] 1160. 拼写单词
    [ 力扣活动0313 ] 169. 多数元素
  • 原文地址:https://www.cnblogs.com/ligen/p/4279218.html
Copyright © 2011-2022 走看看