蛇形矩阵问题。

import java.io.*;
public class SnakeMatrix // 蛇形矩阵
{
 public static void main(String[] args) throws IOException
 {
  new CarryOut().Execute();
 }
}
class CarryOut
{
 public void Execute() throws IOException
 {
  BufferedReader ch=new BufferedReader(new InputStreamReader(System.in));
  System.out.print("请输入一个数:");
  int n=Integer.parseInt(ch.readLine()); // n == 4
  int[][] nn=new int[n][n];//定义一个二维数组
  int number=1;
  int t=0;
  int tt=1;
  if(n==1)
  {
   System.out.print(1);
   return ;
  }
  while(true)
  {
   for(int i=t;i<=n-tt;i++) // 上
   {
    nn[t][i]=number++;
   }
   for(int k=tt;k<n-tt;k++) // 右
   {
    nn[k][n-tt]=number++;
   }
   for(int l=n-tt;l>=t;l--) // 下
   {
    nn[n-tt][l]=number++;
   }
   for(int j=n-tt-1;j>t;j--) // 左
   {
    nn[j][t]=number++;
   }
   t++;
   tt++;
   if(t>=n/2)
   {
    break;
   }
  }
  if(n%2!=0)
  {
   nn[t][t]=number;
  }
  for(int i=0;i<n;i++)
  {
   for(int j=0;j<n;j++)
   {
    System.out.print(String.format("%-5d", nn[i][j]).toString());
   }
   System.out.println();
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值