给定一个正整数 n,生成一个方形矩阵,并使用 1 到 n2 以螺旋顺序填充。

举例:
输入: 3
输出: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

在做完了上一个螺旋矩阵的题后,做这个题就很简单了,因为上一题用到的思路这个题同样适用,只是把读取值换为了写入,毫无难度😂,甚至在代码上可以比上一个题更简单些,因为是方形矩阵,就不需要 length 了。

/*
 * 59. Spiral Matrix II
 * https://leetcode.com/problems/spiral-matrix-ii/
 * https://realneo.me/59-spiral-matrix-ii/
 */

public class GenerateMatrix {
    public static void main(String[] args) {
        GenerateMatrix solution = new GenerateMatrix();

        int[][] result = solution.generateMatrix(3);
        solution.print(result);
        result = solution.generateMatrix(6);
        solution.print(result);
    }

    private int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];

        int i = 0, j = -1;
        int target = n * n;

        for (int x = 1, value = 1, direction = 0; value <= target; x++, direction++) {
            for (int step = 0; step < n - x / 2; step++, value++) {
                switch (direction % 4) {
                    case 0: j++; break;
                    case 1: i++; break;
                    case 2: j--; break;
                    case 3: i--; break;
                }
                matrix[i][j] = value;
            }
        }

        return matrix;
    }

    private void print(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        System.out.println("[");
        for (int i = 0; i < m; i++) {
            System.out.print(" [");
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j]);
                if (j < n - 1)
                    System.out.print(", ");
            }
            System.out.print("]");
            if (i < m - 1)
                System.out.print(",");
            System.out.println();
        }
        System.out.println("]");
    }
}