二维数组的旋转赋值递归

28次阅读

共计 920 个字符,预计需要花费 3 分钟才能阅读完成。

描述

 给定一个 h 行 h 列的整数数组 array,要求从 array[0][0] 元素开始,按回形从外向内顺时针顺序赋值整个数组。如图所示:![图片描述][1]
输出结果:4 4
    1  2  3  4
    12 13 14 5
    11 16 15 6
    10 9  8  7


public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
        int h = scanner.nextInt();// 输入二维数组长度
        int[][] arr = new int[h][h];// 创建二维数组
        setWay(arr,0,0);// 赋值
        for (int[] p : arr) {// 遍历
            for (int p1 : p) {System.out.printf("%-4d",p1);
            }
            System.out.println();}
        System.out.println(t);
    }
    static int p = 1;// 所赋的值
    static int f = 0;// 控制转向  0 为右 1 为下 2 为左 3 为上
    static int t = 0;// 纪录函数调用次数
    public static boolean setWay(int[][]map,int i,int j){if(i==map.length || j ==map.length || i == -1 || j == -1){// 若超出数组
                f = (f+1)%4;// 转向
                t++;
                return false;
            }

            if (map[i][j] == 0) {// 若当前点没有走过
                map[i][j] = p;// 赋值
                p++;
                while(p != map.length*map.length+1)// 输出到最后一个数跳出循环转向
                    switch(f){
                    case 0:
                        if (setWay(map, i, j + 1)) {// 向右走
                            return true;
                        }
                        break;
                    case 1:
                        if (setWay(map, i+1, j)) {// 向下走
                            return true;
                        }
                        break;
                    case 2:
                        if (setWay(map, i , j-1)) {// 向左走
                            return true;
                        } 
                        break;
                    case 3:
                         if (setWay(map, i-1, j)) {// 向上走
                                return true;
                            }
                        break;
                    }
            }
            f = (f+1)%4;// 循环转向
            t++;
            return false;
    }

正文完
 0