数组——螺旋矩阵II

文章目录

题目顺序:代码随想录算法公开课,b站上有相应视频讲解

一、题目

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

二、题解

循环不变量

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n,0));
        int startX = 0,startY = 0,offset = 1,count = 1;
        int i,j;
        int loops = n / 2;
        while(loops--){
            i = startX,j = startY;
            for(j = startY;j < n - offset;j++) res[i][j] = count++;
            for(i = startX;i < n - offset;i++) res[i][j] = count++;
            for(;j > startY;j--) res[i][j] = count++;
            for(;i > startX;i--) res[i][j] = count++;
            startX++;
            startY++;
            offset++;
        }
        if(n % 2 == 1) res[n/2][n/2] = count;
        return res;
    }
};
相关推荐
风暴之零2 分钟前
变点检测算法PELT
算法
深鱼~2 分钟前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果3 分钟前
【PTA】L1-019 谁先倒
数据结构·算法
MSTcheng.3 分钟前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
愚者游世5 分钟前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
小镇敲码人7 分钟前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann
梵刹古音8 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
啊阿狸不会拉杆25 分钟前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
liu****41 分钟前
2.深入浅出理解虚拟化与容器化(含Docker实操全解析)
运维·c++·docker·容器·虚拟化技术
A9better1 小时前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习