【做题也是一场游戏】59. 螺旋矩阵 II

301 阅读1分钟

题目地址

leetcode-cn.com/problems/sp…

题目描述

给你一个正整数 n ,生成一个包含 1 到 n2n^2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix。

示例 1:

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

示例 2:

输入:n = 1 输出:[[1]]  

提示:

1 <= n <= 20

题解

【做题也是一场游戏】54. 螺旋矩阵 类似,进行模拟遍历,一种是借助一个矩阵记录是否访问,由于填入的数据是从1开始的正整数,那么0一定是未访问的,那么这个访问记录矩阵也就是结果,所以不需要额外借助空间; 一种是原地层次遍历。由于生成的矩阵是 n x n 的方阵,不需要考虑单行和单列的情况

借助访问矩阵

class Solution {
    public int[][] generateMatrix(int n) {
        int maxNum = n * n;
        int curNum = 1;
        int[][] matrix = new int[n][n];
        int row = 0, column = 0;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 右下左上
        int 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 = row + directions[directionIndex][0];
            column = column + directions[directionIndex][1];
        }
        return matrix;
    }
}

复杂度分析

  • 时间复杂度:O(n2)O(n^2),其中 n 是给定的正整数。矩阵的大小是 n×nn \times n,需要填入矩阵中的每个元素。

  • 空间复杂度:O(1)O(1)。除了返回的矩阵以外,空间复杂度是常数。

按层次遍历

class Solution {
    public int[][] generateMatrix(int n) {
        if (n <= 0) {
            return new int[][]{};
        }
        int left  = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        int value = 1;

        int[][] result = new int[n][n];
        while(left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                result[top][column] = value++;
            }

            for (int row = top + 1; row <= bottom; row++) {
                result[row][right] = value++;
            }

            for (int column = right - 1; column >= left; column--) {
                result[bottom][column] = value++;
            }

            for (int row = bottom - 1; row > top; row--) {
                result[row][left] = value++;
            }

            left++;
            right--;
            top++;
            bottom--;

        }

        return result;
    }
}

复杂度分析

  • 时间复杂度:O(n2)O(n^2),其中 n 是给定的正整数。矩阵的大小是 n×nn \times n,需要填入矩阵中的每个元素。

  • 空间复杂度:O(1)O(1)。除了返回的矩阵以外,空间复杂度是常数。