首页 > 代码库 > 旋转二维数组

旋转二维数组

 1 package test; 2 /* 3  *     1    2    3    4    5     4  *    16    17    18    19    6     5  *    15    24    25    20    7     6  *    14    23    22    21    8     7  *    13    12    11    10    9 8  *  9  *    写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。10  * */11 public class Test612 {13     public static void main(String[] args)14     {15         arraynum(4);16     }17     // 便于改代码..输入不同y值输出不同的二维数列18     private static void arraynum(int x)19     {20         int[][] arr = new int[x][x];21         int len = arr.length, max = 0, count = 0;22         specArr(arr, len, max, count);23         arrprint(arr);24     }25     // 高级for输出打印用的26     private static void arrprint(int[][] arr)27     {28         for (int[] in : arr)29         {30             for (int t : in)31             {32                 System.out.print(t + "\t");33             }34             System.out.println();35         }36     }37     private static void specArr(int[][] arr, int len, int max, int count)38     {39         while (len > 0)40         {41             int j = 0;42             for (int index = 0; index < (len - 1) * 4; index++)43             {44                 if (index < len - 1)45                     arr[0 + count][index + count] = ++max;46                 else if (index < 2 * (len - 1))47                     arr[count + j++][arr.length - 1 - count] = ++max;48                 else if (index < 3 * (len - 1))49                     arr[arr.length - 1 - count][(j--) + count] = ++max;50                 else if (index < 4 * (len - 1))51                     arr[arr.length - 1 - (j++) - count][0 + count] = ++max;52             }53             if (len == 1)54             {55                 arr[arr.length / 2][arr.length / 2] = max + 1;56             }// 注意到 当y值为奇数时,会有循环到n=1的情况,需要补进数组最中间值57             count++;58             len = len - 2;59         }60     }61 }

 

旋转二维数组