数组——螺旋矩阵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;
    }
};
相关推荐
SY师弟8 分钟前
51单片机基础部分——矩阵按键检测
嵌入式硬件·矩阵·51单片机
csdnzzt10 分钟前
从内存角度透视现代C++关键特性
c++
jie1889457586637 分钟前
C++ 中的 const 知识点详解,c++和c语言区别
java·c语言·c++
Yxh1813778455440 分钟前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
明月*清风43 分钟前
c++ —— 内存管理
开发语言·c++
WindSearcher1 小时前
大模型微调相关知识
后端·算法
取酒鱼食--【余九】1 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar
西北大程序猿2 小时前
单例模式与锁(死锁)
linux·开发语言·c++·单例模式
qq_454175792 小时前
c++学习-this指针
开发语言·c++·学习
Magnum Lehar3 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎