描述数组
给定一个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; }