【Leetcode 每日一题】59. 螺旋矩阵 II-具体实现

时间:2025-02-08 10:10:45
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;
    }
}