本帖最后由 袁世宇 于 2011-11-22 16:27 编辑
- 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[i][j]==0;j++){
- this.array[i][j]= ++this.currentNum;
- }
- // 调整位置。
- i++ ; j--;
- // 从上到下填充。
- for(;i<this.array.length && this.array[i][j]==0;i++){
- this.array[i][j] = ++this.currentNum;
- }
- // 调整位置。
- i--; j--;
- // 从右到左填充。
- for(;j>=0 && this.array[i][j]==0;j--){
- this.array[i][j] = ++this.currentNum;
- }
- // 调整位置。
- j++; i--;
- // 从下到上填充。
- for(;i>=0&&this.array[i][j] ==0;i--){
- this.array[i][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();
- }
- }
- }
复制代码 只要还是递归。这个方阵看起来是一个 回 字。 所以先遍历外面的一圈口 然后再递归里面的几圈口。
这个感觉还是有点面对过程。谁能用面对对象把代码简化一下。 |