写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
- import java.util.Scanner;
- public class Spiral
- {
- public static void main(String[] args)
- {
- System.out.print("请输入打印二维数组的长度:");
- int length = 0;
- Scanner sc = new Scanner(System.in);
- length = sc.nextInt();
- sc.close();
- int[][] matrix = new int[length][length];
- int count = 0,start = 0,value = 1,temp = 0;
- count = (length + 1) / 2;
- for(int i = 0;i < count;i++)
- {
- Spiral sp = new Spiral();
- temp = sp.build(matrix,start,value,length);
- value = temp;
- start++;
- }
- for(int i = 0;i < length;i++)
- {
- for(int j = 0;j < length;j++)
- System.out.print(matrix[i][j] + "\t");
- System.out.print("\n");
- }
- }
-
- public int build(int[][] matrix, int start, int value, int length)
- {
- int i = 0,j = 0;
- for(i = start;i < length;i++)
- {
- if(matrix[start][i] != 0)
- break;
- else
- matrix[start][i] = value++;
- }
- i--;
- for(j = start + 1;j < length;j++)
- {
- if(matrix[j][i] != 0)
- break;
- else
- matrix[j][i] = value++;
- }
- j--;
- for(i--;i >= start;i--)
- {
- matrix[j][i] = value++;
- }
- i++;
- for(j--;j > start;j--)
- {
- matrix[j][i] =value++;
- }
- return value;
- }
- }
复制代码
如有更好的算法欢迎交流!!!
|
|