java旋转二维数组实例

Java是如何运用旋转二维数组呢?下面小编为大家整理了java旋转二维数组实例,希望能帮到大家!

java旋转二维数组实例

复制代码 代码如下:

package test;

/*

* 1 2 3 4 5

* 16 17 18 19 6

* 15 24 25 20 7

* 14 23 22 21 8

* 13 12 11 10 9

*

* 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。

* */

public class Test6

{

public static void main(String[] args)

{

arraynum(4);

}

// 便于改代码..输入不同y值输出不同的'二维数列

private static void arraynum(int x)

{

int[][] arr = new int[x][x];

int len = th, max = 0, count = 0;

specArr(arr, len, max, count);

arrprint(arr);

}

// 高级for输出打印用的

private static void arrprint(int[][] arr)

{

for (int[] in : arr)

{

for (int t : in)

{

t(t + "t");

}

tln();

}

}

private static void specArr(int[][] arr, int len, int max, int count)

{

while (len > 0)

{

int j = 0;

for (int index = 0; index < (len - 1) * 4; index++)

{

if (index < len - 1)

arr[0 + count][index + count] = ++max;

else if (index < 2 * (len - 1))

arr[count + j++][th - 1 - count] = ++max;

else if (index < 3 * (len - 1))

arr[th - 1 - count][(j--) + count] = ++max;

else if (index < 4 * (len - 1))

arr[th - 1 - (j++) - count][0 + count] = ++max;

}

if (len == 1)

{

arr[th / 2][th / 2] = max + 1;

}// 注意到 当y值为奇数时,会有循环到n=1的情况,需要补进数组最中间值

count++;

len = len - 2;

}

}

}