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如何实现啊???? 希望大家帮忙,谢谢了!!!!!
这样写那里不对?????
import java.util.Scanner;
public class Test55fangzhen {
public static void main(String[] args) {
int[][] a=new int[5][5];
int i,j,k=0,m,n;
Scanner in=new Scanner(System.in );
System.out.println( "name ");
n=in.nextInt();
if(n%2==0)m=n/2;
else m=n/2+1 ;
for(i=0;i <m;i++){
for(j=i;j <n;j++){k++;a[i][j]=k;}
for(j=i+1;j <n-i;j++){k++;a[i][j]=k;}
for(j=n-i-2;j> =i;j--){k++;a[n-i-1][j]=k;}
for(j=n-i-2;j> =i;j--){k++;a[j][i]=k;}
}
for(i=0;i <a.length;i++)
{ for(j=0;j <a[1].length;j++)
System.out.print( "\t "+a[i][j]);
System.out .println();
}
}
}
------解决方案--------------------
http://community.csdn.net/Expert/TopicView3.asp?id=5323590
呵呵,好象很多人问这类问题.
还有for循环尽量少套几层,
想别的办法代替,
要不容易出现溢出问题.
:)
------解决方案--------------------
public class Turner {
public final int right=1;
public final int down=2;
public final int left=3;
public final int up=4;
public void printSnake(int n,int type) {
int legs=(int) Math.sqrt(n);
int[][] snake=new int[legs][legs];
for(int j=0; j <legs; j++)
for(int k=0; k <legs; k++)
snake[j][k]=0;
int i=0;
int direct=0;
int x=0;
int y=0;
if(type==1)
direct=right;
else
direct=down;
while(i <n) {
i++;
snake[y][x]=i;
if(type==1) {
if((direct==right && x==legs-1) ||(direct==right && snake[y][x+1]> 0))
direct=down;
if((direct==down && y==legs-1) || (direct==down && snake[y+1][x]> 0))
direct=left;
if((direct==left && x==0) || (direct==left && snake[y][x-1]> 0))
direct=up;
if((direct==up && y==0) || (direct==up && snake[y-1][x]> 0))
direct=right;
} else {
if((direct==right && x==legs-1) ||(direct==right && snake[y][x+1]> 0))
direct=up;
if((direct==down && y==legs-1) || (direct==down && snake[y+1][x]> 0))
direct=right;
if((direct==left && x==0) || (direct==left && snake[y][x-1]> 0))
direct=down;
if((direct==up && y==0) || (direct==up && snake[y-1][x]> 0))