螺旋矩阵

 螺旋矩阵如下:

 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

package com.xue.test;
import java.util.Scanner;
public class ScrewRect {
    private static Scanner scanner;
    public static void main(String[] args) {
        while (true) {
            System.out.print("请输入整数:");
            scanner = new Scanner(System.in);
            int number = scanner.nextInt();
            if (number < 0) {
                System.out.println("输入数值有误!");
                continue;
            }
            int[][] array = getArray(number);
            int n = ("" + number * number).length() + 1;
            for (int i = 0; i < number; i++) {
                for (int j = 0; j < number; j++) {
                    System.out.printf("%" + n + "d", array[i][j]);
                }
                System.out.println();
            }
        }
    }
    private static int[][] getArray(int number) {
        int[][] array = new int[number][number];
        int num = 1;
        int i = 0;
        int j = 0;
        for (int k = 0; k <= number / 2; k++) {
            for (i = k, j = k; j < number - k; j++) { //控制上
                array[i][j] = num++;
            }
            for (i = i + 1, j = j - 1; i < number - k; i++) { //控制右
                array[i][j] = num++;
            }
            for (i = i - 1, j = j - 1; j > k - 1; j--) { // 控制下
                array[i][j] = num++;
            }
            for (i = i - 1, j = j + 1; i > k; i--) { // 控制左
                array[i][j] = num++;
            }
        }
        return array;
    }
}

以上算法源自网络,源头勿追...^-^

你可能感兴趣的:(螺旋矩阵)