Java rotates a two dimensional array instance
- 2020-04-01 03:31:53
- OfStack
This article is an example of how to rotate a two-dimensional array in Java. The specific implementation method is as follows:
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
*
* Write a method to print a two-dimensional array of equal length from 1 The starting natural Numbers are ordered by the outermost circle of the square matrix spiraling inward.
* */
public class Test6
{
public static void main(String[] args)
{
arraynum(4);
}
//Easy to change the code.. Input different y value output different two-dimensional sequence
private static void arraynum(int x)
{
int[][] arr = new int[x][x];
int len = arr.length, max = 0, count = 0;
specArr(arr, len, max, count);
arrprint(arr);
}
//Advanced for output printing with
private static void arrprint(int[][] arr)
{
for (int[] in : arr)
{
for (int t : in)
{
System.out.print(t + "t");
}
System.out.println();
}
}
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++][arr.length - 1 - count] = ++max;
else if (index < 3 * (len - 1))
arr[arr.length - 1 - count][(j--) + count] = ++max;
else if (index < 4 * (len - 1))
arr[arr.length - 1 - (j++) - count][0 + count] = ++max;
}
if (len == 1)
{
arr[arr.length / 2][arr.length / 2] = max + 1;
}//Notice that when y is odd, there is a loop to n=1, and you need to fill in the middle of the array
count++;
len = len - 2;
}
}
}
I hope this article has been helpful to your Java programming.