数组——螺旋矩阵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;
    }
};
相关推荐
好好沉淀16 分钟前
主键选择(自增 vs UUID vs 雪花算法)
java·算法
郝学胜-神的一滴1 小时前
中级OpenGL教程 023:Assimp模型加载全解——从源码到架构的骈文探秘
c++·unity·游戏引擎·cmake·unreal engine·opengl
星恒随风1 小时前
C++ STL 详解:list 的使用、迭代器失效、模拟实现与 vector 对比
开发语言·数据结构·c++·笔记·学习·list
退休倒计时1 小时前
【每日一题】LeetCode 131. 分割回文串 TypeScript
算法·leetcode·typescript
小白说大模型1 小时前
AI Agent 调试实战:链路追踪、Prompt 可视化与异常定位的系统方法
java·人工智能·python·算法·prompt
梅梅绵绵冰1 小时前
算法题-矩阵
数据结构·算法·矩阵
牢姐与蒯1 小时前
c++之异常
开发语言·c++·c++11
此生决int1 小时前
深入理解C++系列(02)——类和对象(上)
开发语言·c++
atunet1 小时前
关于从哈希冲突看缓存设计的实践与权衡7
算法
zjun10012 小时前
C++:单例模式
c++·单例模式