LeetCode —— 59. 螺旋矩阵 II

109 阅读2分钟

启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第13天,点击查看活动详情

该题是螺旋数组题型第一题。

题目来源

59. 螺旋矩阵 II - 力扣(LeetCode)

题目描述(中等

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

示例1

spiraln.jpg

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

示例2

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

提示

  • 1<=n<=201 <= n <= 20

题目解析

该题可以理解为从一个正方形( n2n^2 个小正方形组成)的左上角的小正方形出发,初始方向为右,在经过的小正方形中,如果没有留下过数字,则会留下数字,如果下一步位置没有小正方形或者这个小正方形已经留下过数字了,就 顺时针旋转九十度 切换方向,直到留下 n2n^2 个数字。

模拟

首先,设定变量 result 为生成的矩阵,初始值为 0 ,由于填入的数字是从 1 开始递增的,我们可以判断当前位置是否存在数字,若不为 undefined ,则说明已经访问过此位置。

代码

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    let result = [], column = 0, row = 0, val = 1, max = n * n, directions = [[0, 1], [1, 0], [0 , -1], [-1, 0]], directionIndex = 0
    for (let i = 0;i < n;i++){
        result.push([])
    }
    while (val <= max) {
        result[row][column] = val
        val++
        let nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1]
        if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || result[nextRow][nextColumn]){
            directionIndex = (directionIndex + 1) % 4
        }
        row += directions[directionIndex][0]
        column += directions[directionIndex][1]
    }
    return result
};
  • 时间复杂度:O(n2)O(n^2),其中 n 是给定的正整数,矩阵大小为 n * n ,需要填入所有元素。
  • 空间复杂度:O(1)O(1)

如图:

image.png

代码(官方)

var generateMatrix = function(n) {
    const maxNum = n * n;
    let curNum = 1;
    const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
    let row = 0, column = 0;
    const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // 右下左上
    let directionIndex = 0;
    while (curNum <= maxNum) {
        matrix[row][column] = curNum;
        curNum++;
        const 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 * n ,需要填入所有元素。
  • 空间复杂度:O(1)O(1)

如图:

image.png

执行用时和内存消耗仅供参考,大家可以多提交几次。如有更好的想法,欢迎大家提出。