数组——螺旋矩阵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;
    }
};
相关推荐
mmmmath_33 小时前
LeetCode.199.二叉树的右视图
数据结构·leetcode
专注仿真3 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸3 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫3 小时前
2028编程圈很火的10个Skills
算法·面试·github
别动我齐刘海5 小时前
Linux 系统调试学习1
linux·运维·服务器·c++·学习·机器学习·机器人
Nil2088 小时前
leetcode 198打家劫舍
算法·leetcode·职场和发展
Shaoshing8 小时前
前缀和与差分
java·数据结构·算法·前缀和·差分
mmmmath_38 小时前
LeetCode.429.N叉树的层序遍历
数据结构·leetcode
loulanyue_9 小时前
构建房产认知决策智能:Harness底座与AI自进化的技术实践——读贝壳首席算法科学家尹俊希2026云栖专场演讲
人工智能·算法
碧海银沙音频科技研究院9 小时前
基于炬芯ATS录音卡BLE控制协议
人工智能·嵌入式硬件·算法·语音识别