codevs 1160 蛇形矩阵

题目描述 Description

小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该n行n列正方形矩阵以及其的对角线数字之和.

输入描述 Input Description

n(即n行n列)

输出描述 Output Description

n+1行,n行为组成的矩阵,最后一行为对角线数字之和

样例输入 Sample Input

3

样例输出 Sample Output

5 4 3
6 1 2
7 8 9
25

数据范围及提示 Data Size & Hint
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<iomanip>
using namespace std;
int a[101][101]={0};
int main()
{
    int n,tot=1;
    cin>>n;
    int i=(n+1)/2;
    int j=(n+1)/2;
    a[i][j]=tot;
    int m=i;
    int p=j;
    for(int w=1;w<=(n-1)/2;w++)
    {
    while(p<j+w)
     {
         tot++;
        p++;
         a[m][p]=tot;
        }    
    while(m>(i-w))
     {
         m--;
         tot++;
         a[m][p]=tot;
          }     
     while(p>j-w)
      {
          p--;
          tot++;
          a[m][p]=tot;
            }
    while(m<i+w)
     {
         m++;
         tot++;
         a[m][p]=tot;
           }
           while(p<j+w)
     {
         tot++;
        p++;
         a[m][p]=tot;
        }
    }    
    int sum=0;          
     for(int i=1;i<=n;i++)
      {
          for( j=1;j<=n;j++)
           {
               if(i==j||i+j==n+1)
                {
                    sum+=a[i][j];
                }
           }  
              }
     for(int i=1;i<=n;i++)
      {
          for( j=1;j<=n;j++)
           {
            cout<<a[i][j]<<" ";
         }
            cout<<endl;    
     }       
     cout<<sum<<endl;
    return 0;          
}

 

posted @ 2017-05-16 20:44  ioioioioioio  阅读(189)  评论(0编辑  收藏  举报