Bootstrap

【Leetcode 每日一题】59. 螺旋矩阵 II

问题背景

给你一个正整数 n n n,生成一个包含 1 1 1 n 2 n ^ 2 n2 所有元素,且元素按顺时针顺序螺旋排列的 n × n n \times n n×n 正方形矩阵 m a t r i x matrix matrix

数据约束

  • 1 × n × 20 1 \times n \times 20 1×n×20

解题过程

定义方向数组,每次遇到越界的情况或是已经填过数字的位置,就变换方向。

具体实现

class Solution {
    private static final int[][] DIRECTIONS = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 0;
        int j = 0;
        int direction = 0;
        // 按要填的数进行循环
        for (int cur = 1; cur <= n * n; cur++) {
            res[i][j] = cur;
            // 根据方向数组,计算下一个该填数的位置
            int x = i + DIRECTIONS[direction][0];
            int y = j + DIRECTIONS[direction][1];
            // 遇到越界的情况,或者下个位置已经填过数,就要变换方向
            if (x < 0 || x >= n || y < 0 || y >= n || res[x][y] != 0) {
                direction = (direction + 1) % 4;
            }
            // 迭代新位置
            i += DIRECTIONS[direction][0];
            j += DIRECTIONS[direction][1];
        }
        return res;
    }
}
;