本帖最后由 袁世宇 于 2011-11-22 16:28 编辑
public class FillArray {
private int[][] array ;
private int max ;
private int currentNum;
public FillArray(int len){
this.array = new int[len][len];
this.max = len*len;
}
public void fill(int i,int j){
// 若数组还没有填充完毕。
if(this.currentNum<this.max){
// 从左到右填充。
for(;j<this.array.length && this.array[j]==0;j++){
this.array[j]= ++this.currentNum;
}
// 调整位置。
i++ ; j--;
// 从上到下填充。
for(;i<this.array.length && this.array[j]==0;i++){
this.array[j] = ++this.currentNum;
}
// 调整位置。
i--; j--;
// 从右到左填充。
for(;j>=0 && this.array[j]==0;j--){
this.array[j] = ++this.currentNum;
}
// 调整位置。
j++; i--;
// 从下到上填充。
for(;i>=0&&this.array[j] ==0;i--){
this.array[j] = ++this.currentNum;
}
// 调整位置。
i++; j++;
// 递归填充。
this.fill(i, j);
}
}
public static void main(String[] args) {
FillArray obj = new FillArray(6);
obj.fill(0, 0);
int[][] array = obj.array;
for(int[] row:array){
for(int col:row){
System.out.print(col+" ");
}
System.out.println();
}
}
} |