[LeetCode] 59. 螺旋矩阵 II

img

1. 问题描述

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

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

示例 1:

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

示例 2:

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

提示:

  • 1 <= n <= 20

2. 实现思路

2.1 自己的思路

~~(一定要写出来啊喂)~

泪目了,遇到模拟题真是最大的幸运(误)

本题的关键点在于边界和如何处理转向

边界不只要考虑数组边界,还要考虑已填充数据作为边界

转向的话可以发现规律:→↓←↑,如此循环,那么假设用0123来表示的话,direction不断+1,然后%4即可

同时可以发现,转向的时候刚好是更新边界的时候。

巨长无比的代码~

/*
 * @lc app=leetcode.cn id=59 lang=csharp
 *
 * [59] 螺旋矩阵 II
 */

var s = new Solution();
s.GenerateMatrix(5);

// @lc code=start
public class Solution
{
    public int[][] GenerateMatrix(int n)
    {
        int[][] result = new int[n][];
        for (int i = 0; i < n; i++)
            result[i] = new int[n];
        int row = 0;
        int col = 0;
        int direction = 0; // 右下左上0123
        int leftBound = 0;
        int rightBound = n - 1;
        int upBound = 0;
        int bottomBound = n - 1;

        for (int i = 1; i <= n * n; i++)
        {
            if (result[row][col] == 0)
                result[row][col] = i;
            else
            {
                // →↓←↑
                direction = (direction + 1) % 4;
                switch (direction)
                {
                    case 0:
                        leftBound++;
                        break;
                    case 1:
                        upBound++;
                        break;
                    case 2:
                        rightBound--;
                        break;
                    case 3:
                        bottomBound--;
                        break;
                }
                i--;
            }
            switch (direction)
            {
                case 0:
                    col = Math.Clamp(col + 1, leftBound, rightBound);
                    break;
                case 1:
                    row = Math.Clamp(row + 1, upBound, bottomBound);
                    break;
                case 2:
                    col = Math.Clamp(col - 1, leftBound, rightBound);
                    break;
                case 3:
                    row = Math.Clamp(row - 1, upBound, bottomBound);
                    break;
            }
        }
        return result;
    }
}
// @lc code=end

2.2 题解思路

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

  • 方法一:模拟,跟我的思路差不多,但是代码更简洁一些:一个是用数组代替direction方便移动,一个是将旋转条件合并
public class Solution {
    public int[][] GenerateMatrix(int n) {
        int maxNum = n * n;
        int curNum = 1;
        int[][] matrix = new int[n][];
        for (int i = 0; i < n; i++) {
            matrix[i] = new int[n];
        }
        int row = 0, column = 0;
        int[][] directions = new int[][] { new int[] { 0, 1 }, new int[] { 1, 0 }, new int[] { 0, -1 }, new int[] { -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 += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return matrix;
    }
}

复杂度分析

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

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

  • 方法二:按层模拟

这里感觉代码随想录上讲的更清晰,就放那边的链接了

59.螺旋矩阵II | 螺旋矩阵 | 模拟 | 循环不变量

public int[][] GenerateMatrix(int n)
{
    // 参考Carl的代码随想录里面C++的思路
    // /algo/array/0059-spiral-matrix-ii.html
    int startX = 0, startY = 0; // 定义每循环一个圈的起始位置
    int loop = n / 2; // 每个圈循环几次,例如n为奇数3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理
    int count = 1; // 用来给矩阵每个空格赋值
    int mid = n / 2; // 矩阵中间的位置,例如:n为3, 中间的位置就是(1,1),n为5,中间位置为(2, 2)
    int offset = 1;// 需要控制每一条边遍历的长度,每次循环右边界收缩一位

    // 构建result二维数组
    int[][] result = new int[n][];
    for (int k = 0; k < n; k++)
    {
        result[k] = new int[n];
    }

    int i = 0, j = 0; // [i,j]
    while (loop > 0)
    {
        i = startX;
        j = startY;
        // 四个For循环模拟转一圈
        // 第一排,从左往右遍历,不取最右侧的值(左闭右开)
        for (; j < n - offset; j++)
        {
            result[i][j] = count++;
        }
        // 右侧的第一列,从上往下遍历,不取最下面的值(左闭右开)
        for (; i < n - offset; i++)
        {
            result[i][j] = count++;
        }

        // 最下面的第一行,从右往左遍历,不取最左侧的值(左闭右开)
        for (; j > startY; j--)
        {
            result[i][j] = count++;
        }

        // 左侧第一列,从下往上遍历,不取最左侧的值(左闭右开)
        for (; i > startX; i--)
        {
            result[i][j] = count++;
        }
        // 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1)
        startX++;
        startY++;

        // offset 控制每一圈里每一条边遍历的长度
        offset++;
        loop--;
    }
    if (n % 2 == 1)
    {
        // n 为奇数
        result[mid][mid] = count;
    }
    return result;
}

2.3 优化(或者敲一遍题解?)


如下,记得i和j不要敲反了

/*
 * @lc app=leetcode.cn id=59 lang=csharp
 *
 * [59] 螺旋矩阵 II
 */

var s = new Solution();
s.GenerateMatrix(2);

// @lc code=start
public class Solution
{
    public int[][] GenerateMatrix(int n)
    {
        // 初始化结果数组
        int[][] ans = new int[n][];
        for (int t = 0; t < n; t++)
            ans[t] = new int[n];

        int startX = 0;
        int startY = 0;
        int offset = 1;
        int i, j;
        int loop = n / 2;
        int mid = n / 2;
        int count = 1;
        while (loop > 0)
        {
            i = startX;
            j = startY;
            // 上
            for (; j < n - offset; j++)
                ans[i][j] = count++;

            // 右
            for (; i < n - offset; i++)
                ans[i][j] = count++;

            // 下
            for (; j > startX; j--)
                ans[i][j] = count++;

            // 左
            for (; i > startY; i--)
                ans[i][j] = count++;

            startX++;
            startY++;
            loop--;
            offset++;
        }

        // 中间值
        if (n % 2 != 0)
            ans[mid][mid] = count;

        return ans;
    }
}
// @lc code=end

3. 补充知识と杂谈,总结

此题主要是模拟题,考查的是对代码的掌控度,坚持循环不变量与左闭右开原则

posted @ 2026-08-10 12:44  绘星tsuki  阅读(4)  评论(0)    收藏  举报