如何以螺旋顺序打印数字? [英] How to print numbers in a spiral order?

查看:134
本文介绍了如何以螺旋顺序打印数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢, 我正在尝试解决项目欧拉问题,它希望我打印

Thank you , i am trying to solve a project euler problem it wants me to print the sum of

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

这是从数字1开始并按顺时针方向向右移动5 x 5矩阵形成的,但是我在编写螺旋矩阵代码时遇到了麻烦!

this is formed by starting with the number 1 and moving to the right in a clockwise direction for a 5 by 5 matrix but i am in trouble writing a code for the spiral matrix !!

推荐答案

强烈建议您自行完成项目Euler问题并寻求帮助,如果您确实遇到困难

It is Highly recommended to do project Euler problems on your own and ask for help if you are really stuck

这是我将如何在c中编写代码以打印问题中建议的螺旋

here is how i will write a code in c to print a spiral as suggested in the question

#include<stdio.h>
main()
{
int i,j,nq=9;//nq is a odd number which represents the order of the matrix
int lim=(int)nq/2,cnt=2;
int a[nq][nq];
 for(i=0;i<nq;i++){
    for(j=0;j<nq;j++)
    a[i][j]=0;
    }
a[lim][lim]=1;
a[lim][lim+1]=2;
int i1=lim,j1=lim+1;i=lim,j=lim;
while(1){
       if(cnt>(nq*nq))
         break;
        cnt++;
if(i==i1)
{  j=j1;
   if(i<=lim)
   {
       i=i1;
    if(a[i1+1][j1]==0)
        a[++i1][j]=cnt;
    else
       a[i1][++j1]=cnt;
   }
   else
   {   i=i1;
    if(a[i1-1][j1]==0)
       a[--i1][j1]=cnt;
    else
        a[i1][--j1]=cnt;
   }
}
else
{   i=i1;
    if(j<lim)
   {
        j=j1;
       if(a[i1][j+1]==0)
        a[i1][++j1]=cnt;
       else
        a[--i1][j1]=cnt;
   }
   else
   {    j=j1;
       if(a[i1][j1-1]==0)
        a[i1][--j1]=cnt;
       else
        a[++i1][j1]=cnt;
   }
  }
}
for(i=0;i<nq;i++){
    for(j=0;j<nq;j++)
    printf(" %d    ",a[i][j]);
    printf("\n");
}

}

我用Google搜索了您的问题 http://projecteuler.net/problem=28 这也可以解决通过利用其数学性质,请注意

I Googled your question http://projecteuler.net/problem=28 this can also be solved by taking advantage of its mathematical nature note that

右上角为n ^ 2 其他角可以显示为n ^ 2-2n + 2,n ^ 2-n + 1和n ^ 2-3n + 3.您只需要总结这些角点

Top right corner is n^2 and other corners can be shown to be n^2-2n+2 ,n^2-n+1, and n^2-3n+3. you just need to sum those corners which comes to be

= 4 * n ^ 2-6 * n + 6

因此,可以通过将第二个数字从1001迭代到3来计算最终答案

hence the final answer can be calculated by iterating over every second number from 1001 to 3

long int sum(int n){
    long int sum=1;
    while(n>1){
      sum=sum+4*n*n-6*n+6;
      n=n-2;
    }
    return sum;
    } 

这篇关于如何以螺旋顺序打印数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆