数学螺旋

来源:互联网 发布:怎么测试网络掉包 编辑:程序博客网 时间:2024/04/28 07:46

package cn.javalife;

public class MathLuooXuan  {

 /**
  * @param args
  */
 final static int s=10;//矩阵长宽
 int map[][]=new int[s][s];
 int mapPass[][]=new int[s][s];
 final int up=0;
 final int right=1;
 final int down=2;
 final int left=3;
 int goX;
 int goY;
 int goWay=right;
 
 
 
 private void check(){
  int px=0;
  int py=0;
  switch(goWay){
  case up:
   py=goY-1;
   px=goX;
   break;
  case down:
   py=goY+1;
   px=goX;
   break;
  case left:
   px=goX-1;
   py=goY;
   break;
  case right:
   px=goX+1;
   py=goY;
   break;
  }
  if(Turn(px,py)){
   goWay++;
   if(goWay>3)
    goWay=0;
  }
 }
 
 
 private void run(){
  for(int i=0;i<s*s;i++){
   this.check();
   mapPass[goX][goY]=1;
   map[goX][goY]=i+1;
   switch(goWay){
   case up:
    goY--;
    break;
   case down:
    goY++;
    break;
   case left:
    goX--;
    break;
   case right:
    goX++;
    break;
   }
   
  }
 }
 
 public boolean Turn(int x,int y){
  
  if(x>=s||y<0||y>=s||x<0)
   return true;
  else{
   if(mapPass[x][y]==1)
    return true;
  }
  return false;
 }
 
 public MathLuooXuan(){
  run();
  for(int y=0;y<s;y++){
   for(int x=0;x<s;x++){
    System.out.print(" "+map[x][y]);
   }
   System.out.println("");
  }
 }
 
 
 
 public static void main(String[] args) {
  // TODO 自动生成方法存根
  MathLuooXuan a=new MathLuooXuan();
  
 }

}