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

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

相关推荐
ynchyong几秒前
培养程序化思维
leetcode·程序化思维·刷题经验
荆棘鸟智能1 小时前
河道采砂船识别与轨迹追踪怎么做?检测、跟踪与电子围栏实战思路
人工智能·算法·目标检测
揽星河..1 小时前
【初阶数据结构】常见的排序算法
数据结构·排序算法·1024程序员节
DFT计算杂谈1 小时前
GSAS-II X 射线衍射(XRD)数据转换为对分布函数(PDF,Pair Distribution Function)
算法·机器学习·pdf
绕灵儿2 小时前
火灾检测-应用场景-YOLO训练记录
人工智能·算法
YLCHUP2 小时前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
啊啊啊啊啊!!!!2 小时前
【c++】⽤哈希表封装myunordered_map和myunordered_set
数据结构·哈希算法·散列表
(●—●)橘子……2 小时前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
Tt有了t2 小时前
Redis的数据结构
数据结构·数据库·redis
Rain的Java大神之路2 小时前
LeetCode 21 合并两个有序链表:一道 Easy 题,凭什么刷掉一半候选人?
java·后端·算法