- public class LineArray {
- /**
- * 螺旋数组的
- *
- * @param args
- */
- public static void main(String[] args) {
- createArray(7,true);//true为顺时针输出,false为逆时针输入
- }
- public static void createArray(int n,boolean flag) {//加入一个标记,可以实现逆时针或者顺时针螺旋输出
- int index = 1;
- Direction dir;
- if(flag)
- dir= Direction.D;
- else dir= Direction.A;
- int[][] arr = new int[n][n];
- int row = n / 2, col = n / 2, temp = 0, step = 0;
- while (index != n * n) {
- // temp=(step%2==0)?temp+1:temp;
- if (step % 2 == 0 && step != (n - 1) * 2)
- temp++;
- if (dir == Direction.D) {
- for (int i = 0; i < temp; i++) {
- arr[row][++col] = ++index;
- }
- step++;
- } else if (dir == Direction.S) {
- for (int i = 0; i < temp; i++) {
- arr[++row][col] = ++index;
- }
- step++;
- } else if (dir == Direction.A) {
- for (int i = 0; i < temp; i++) {
- arr[row][--col] = ++index;
- }
- step++;
- } else if (dir == Direction.W) {
- for (int i = 0; i < temp; i++) {
- arr[--row][col] = ++index;
- }
- step++;
- }
- dir = dir.nextDirection(flag);
- for (int i = 0; i < arr.length; i++)
- System.out.println(Arrays.toString(arr[i]));
- System.out.println("----------------------------------------");
- }
- }
- }
- enum Direction {
- D, S, A, W;// 四个方向,螺旋数组的行走方向
- public Direction nextDirection(boolean flag) {// 循环四个方向
- if(flag){
- switch (this) {
- case D: return S;
- case S: return A;
- case A: return W;
- case W: return D;
- }
- } else {
- switch (this) {
- case A: return S;
- case S: return D;
- case D: return W;
- case W: return A;
- }
- }
- return null;
- }
-
- }
复制代码 因为枚举方向的变化控制,所以简单实现了,程序的逆时针与逆时针的分别输出.- ----------------------------------------
- [25, 24, 23, 22, 21]
- [10, 9, 8, 7, 20]
- [11, 2, 0, 6, 19]
- [12, 3, 4, 5, 18]
- [13, 14, 15, 16, 17]
- ----------------------------------------
复制代码 |