输入5和输入6输出效果如图:
java源代码如下:
package com.jiucaiyuan.recurse;
public class TestSquare {
public static int a[][];
public static void main(String[] args) {
calc(5);
print();
System.out.println("===================================");
calc(6);
print();
}
private static void print() {
if (a==null) return;
for (int i=0;i<a.length;i++){
for (int j=0;j<a[0].length;j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
System.out.println();
}
}
public static int[][] calc(int lengthOfSide){
if(lengthOfSide == 0){
a = new int[][]{{0}};
return a;
}
a = new int[lengthOfSide][lengthOfSide];
int currValue = 1;
int level =0;
putValueToArray1(currValue,level);
return a;
}
private static void putValueToArray1(int currValue,int level) {
if (a.length%2==0){
if (level == a.length/2-1){
a[level][level] = currValue++;
a[level][level+1] = currValue++;
a[level+1][level+1] = currValue++;
a[level+1][level] = currValue++;
return;
}
}else{
if (level == (a.length+1)/2 - 1){
a[level][level] = currValue;
return;
}
}
//横向右
for (int i=level;i<a.length - level;i++){
a[level][i]=currValue;
currValue++;
}
//竖向下
for (int i=level+1;i<a.length-level;i++){
a[i][a.length-level-1]=currValue;
currValue++;
}
//横向左
for (int i=a.length-level-2;i>level-1;i--){
a[a.length-level-1][i]=currValue;
currValue++;
}
//竖向上
for (int i=a.length - level - 2;i>level ;i--){
a[i][level]=currValue;
currValue++;
}
putValueToArray1(currValue,level+1);
}
}