移动轨迹:下—>左—>上—>右 循环。。。。越界或者走到以前的格子都要停下来。
代码:
shexing类
package pack1;
public class shexing {
private int [][]a=new int[10][10];
private int n;
private int tot;
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public shexing() {
super();
}
public void set_shexing(){
int tot=1;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
a[i][j]=0;
int x=0,y=n-1;
a[x][y]=1;
while(tot<n*n){
while(x+1<n && a[x+1][y]==0)
a[++x][y]=++tot;
while(y-1>=0 && a[x][y-1]==0)
a[x][--y]=++tot;
while(x-1>=0 && a[x-1][y]==0)
a[--x][y]=++tot;
while(y+1<n && a[x][y+1]==0)
a[x][++y]=++tot;
}
}
public void display(){
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.format("%3s",a[i][j]);
System.out.println();
}
}
}
testshexing类:
package pack1;
import java.util.Scanner;
public class testshengxing {
public static void main(String[] args) {
int n;
shexing s=new shexing();
Scanner in=new Scanner(System.in);
System.out.println("请输入一个小于10的整数:\n");
n=in.nextInt();
s.setN(n);
s.set_shexing();
System.out.println("输出的的蛇形填数为:\n");
s.display();
}
}
运行结果: