- package day04;
- /**
- * 输出 n=5 的螺旋方阵
- * 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
- * @author bilibili
- *
- */
- class SpiralMatrix {
- /**
- *
- * @param order 输入螺旋方阵的阶数(层数)
- */
- public void print(int order) {
- int start = 0, end = order - 1, count = 1, i;
- int[][] arr = new int[order][order];
- /* 将螺旋方阵一层一层赋值到二维数组 */
- while (start <= end) {
- for (i = start; i <= end; i++) {
- arr[start][i] = count++;
- }
- for (i = start + 1; i <= end; i++) {
- arr[i][end] = count++;
- }
- for (i = end - 1; i >= start; i--) {
- arr[end][i] = count++;
- }
- for (i = end - 1; i > start; i--) {
- arr[i][start] = count++;
- }
- start++;
- end--;
- }
- /* 打印螺旋方阵 */
- for (i = 0; i < order; i++) {
- for (int j = 0; j < order; j++) {
- System.out.print(arr[i][j] + "\t");
- }
- System.out.println();
- }
- }
- }
复制代码 |