数组——螺旋矩阵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;
    }
};
相关推荐
INS_KF16 分钟前
【C++知识杂记2】free和delete区别
c++·笔记·学习
一只鱼^_24 分钟前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!25 分钟前
【动态规划】斐波那契数列模型
算法·动态规划
ikkkkkkkl26 分钟前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
啊阿狸不会拉杆1 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
重启的码农1 小时前
ggml介绍 (8) 图分配器 (ggml_gallocr)
c++·人工智能·神经网络
火车叨位去19491 小时前
力扣top100(day04-05)--堆
算法·leetcode·职场和发展
数据智能老司机1 小时前
面向企业的图学习扩展——面向图的传统机器学习
算法·机器学习
重启的码农1 小时前
ggml介绍 (9) 后端调度器 (ggml_backend_sched)
c++·人工智能·神经网络
类球状1 小时前
顺序表 —— OJ题
算法