59. Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

复制代码
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

复制代码
Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

    class Solution {
    public:
    vector<vector> generateMatrix(int n) {
    vector<vector>nums(n,vector(n,0));
    int StartX=0,StartY=0;
    int count=1;
    int offset=1;
    int loop=n/2;
    while(loop--){
    int i,j;
    for(j=StartY;j<n-offset;j++){
    nums[StartX][j]=count++;
    }
    for(i=StartX;i<n-offset;i++){
    nums[i][j]=count++;
    }
    for(;j>StartY;j--){
    nums[i][j]=count++;
    }
    for(;i>StartX;i--){
    nums[i][j]=count++;
    }
    StartX++;
    StartY++;
    offset++;
    }
    if(n%2==1){
    nums[n/2][n/2]=count;
    }
    return nums;
    }
    };

注意:

1.offset的初始值,其实就是因为数组的行和列都是从0开始的

2.注意边界条件,数组别越界了

3.每旋转一圈StartX、StartY和offset都要+1

4.总体思路是用到了左闭右开的原则,这点参考二分查找,每行每列的最后一个元素都是交给下一个循环的时候做

这道题的算法很简单,就是需要处理的边界条件有点绕,很容易没注意到就错了,小心数组的越界

相关推荐
啊嘞嘞?3 小时前
力扣(LRU缓存)
算法·leetcode
珂朵莉MM3 小时前
2026国信杯具身智能创新大赛-编程技能赛--本科组国赛解题报告 | 珂学家
算法·深度优先·图论
啊嘞嘞?3 小时前
力扣(下一个排列)
算法·leetcode
李可以量化4 小时前
Redis Client 从入门到精通(一)下:redis-py 核心数据结构操作与连接管理
数据结构·redis·python·bootstrap·量化交易·qmt
疯狂打码的少年4 小时前
【数据结构】复习日:树 + 图 + 排序(整理对比表)
数据结构·笔记·算法
benchmark_cc4 小时前
Claude Code + MCP + QuantDash:打造全自动量化研究流水线的终极指南
人工智能·后端·爬虫·算法·claude·mcp·quantdash
星星.7224 小时前
2026河南萌新联赛第六场(郑州大学)补题B、D、L、J、I
数据结构·c++·算法
朝发如雪4 小时前
快速掌握Linux(2)(时间相关函数)(文件IO)
linux·python·算法
Forever Nore4 小时前
LeetCode 16 最接近的三数之和 - 双指针逼近
算法·leetcode·职场和发展
心仪久了会沦陷4 小时前
数据结构入门系列——顺序表详解:概念、分类与动态实现
c语言·数据结构·经验分享·笔记·开源