0
点赞
收藏
分享

微信扫一扫

LeetCode 螺旋矩阵 II


螺旋矩阵 II:

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

LeetCode 螺旋矩阵 II_后端

示例 1:

输入:​​n = 3​

输出:​​[[1,2,3],[8,9,4],[7,6,5]]​

示例 2:

输入:​​n = 1​

输出:​​[[1]]​

提示:

​1 <= n <= 20​

题解

解题分析

题解思路

  1. 模拟矩阵的生成。按照要求,初始位置设为矩阵的左上角,初始方向设为向右。若下一步的位置超出矩阵边界,或者是之前访问过的位置,则顺时针旋转,进入下一个方向。如此反复直至填入 n^2 个元素。
  2. 记 ​​matrix​​ 为生成的矩阵,其初始元素设为 ​​0​​。由于填入的元素均为正数,我们可以判断当前位置的元素值,若不为 ​​0​​,则说明已经访问过此位置。

复杂度分析

  • 时间复杂度:O(N^2)
  • 空间复杂度:O(1)

解题代码

题解代码如下(代码中有详细的注释说明):

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) {
// 右上角从 1 开始
matrix[row][column] = curNum;
// 当前值累加
curNum++;

// 计算下一个单元格的位置
int nextRow = row + directions[directionIndex][0];
int 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;
}
}

提交后反馈结果:

LeetCode 螺旋矩阵 II_Java_02

参考信息

  • ​​力扣(LeetCode)59 题: 螺旋矩阵 II​​
举报

相关推荐

0 条评论