LeetCode59(2021.3.16)

LC59. 螺旋矩阵 II

class Solution {
    public int[][] generateMatrix(int n) {
        int maxNum = n * n, curNum = 1;
        int[][] matrix = new int[n][n];
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int row = 0, column = 0, directionIndex = 0;
        while (curNum <= maxNum) {
            matrix[row][column] = curNum;
            curNum++;
            int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
                directionIndex = (directionIndex + 1) % 4; //顺时针旋转
            }
            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return matrix;
    }
}

留下评论