N*N螺旋方阵

编程实现N*N螺旋方阵:

如输入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


代码实现:

Java:

//用direction代表方向,0为右,1为下,2为左,3为上

import  java.util.Scanner;

 

publicclassWelcome{

 

    public static void main(String[] args)

    {

       Scanner input=new Scanner(System.in);

       System.out.print("Pleaseinput the rowlength of the matrix: ");

       int ninput.nextInt();

       int Nn;

       int count n*n;

       int direction 0;

       int [][] matrix new int[n][n];

       int row 0;

       int col 0;

       for(int k=1;k<=count;k++)

           switch(direction)

           {

           case0:

              matrix[row][col]=k;

              if(col==n-1)

                  {

                  direction=1;

                  ++row;

                  break;

                  }

              ++col;

              break;

             

           case1:

              matrix[row][col]=k;

              if(row==n-1)

              {

                  --col;

                  direction=2;

                  break;

              }

              ++row;

              break;

             

           case2:

             

              matrix[row][col]=k;

              if(col==N-n)

              {

                  --row;

                  direction=3;

                  break;

              }

              --col;

              break;

             

           case3:

              matrix[row][col]=k;

              if(row==N-n+1)

              {

                  ++col;

                  direction=0;

                  --n;

                  break;

              }

              --row;

              break;

             

           }

       System.out.println();

      

       for(inti=0;i<N;i++)

           for(intj=0;j<N;j++)

              {

               System.out.print(matrix[i][j]+"   ");

               if(j==N-1)System.out.println();

              }

              

    }


在网上找到了几篇不错的相关的文章,贴在这里:

n阶螺旋方阵的算法分析

http://wenku.baidu.com/link?url=39oCQYJfH5--fBGG5s4tINlYit1Db_gsixQ90J_bnr0NAqS3QRYJPMovitBApAF0jIHl4eh6dmqEkwJXeIa5yDJBjgFkdRB0wVlRfpBvU2S                       

C++打印螺旋方阵

http://zhidao.baidu.com/link?url=iC6uBz_cTgRIxdlSJ1f9w4_RByNja1208-uYbd4sy_gU9-pLq_jSSu7pErIwyk1O2sIP6ytFXIfs02ddeym3k9p8o1l_avPwAvpaNMdfra_           


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值