當前位置:才華齋>計算機>java語言>

java旋轉二維陣列例項

java語言 閱讀(6.98K)

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;

}

}

}