日期:2014-05-20  浏览次数:20852 次

救助
17 16 15 14 13
18 5  4   3 12
19 6  1   2 11
20 7  8   9 10
21 22 23 24 25
当n值不同时如何输出
算法,JAVA

------解决方案--------------------

public static void main(String[] args){
System.out.println("请输入n,按回车完成输入:");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] a = new int[n][n];
int max = n * n;
int row = 0, col = 0;
int direction = 0;
if (n%2==0) {
row = (n/2)-1;
col = (n/2)-1;
} else {
row = (n-1)/2;
col = (n-1)/2;
}
for (int i = 1; i <= max; i++) {
a[row][col] = i;
switch (direction) {
case 0:
if(i<max&&a[row+1][col+1]==0){
direction += 1;
direction %= 4;
}
col++;
break;
case 1:
if(i<max&&a[row+1][col-1]==0){
direction += 1;
direction %= 4;
}
row++;
break;
case 2:
if(i<max&&a[row-1][col-1]==0){
direction += 1;
direction %= 4;
}
col--;
break;
case 3:
if (i<max&&a[row-1][col+1]==0) {
direction += 1;
direction %= 4;
}
row--;
break;
default:
System.out.println("你进入了异度空间。。。四边形你却找到了第五条边!");
System.exit(0);
}
}
String string = new String();
String mStr = String.valueOf(max);
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
string = String.valueOf(a[j][k]);
while(mStr.length()>string.length()){
string = "0"+string;
}
System.out.print(" "+string);
}
System.out.println("");
}
}