数组——螺旋矩阵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;
    }
};
相关推荐
水云桐程序员17 小时前
C++可以写手机应用吗
开发语言·c++·智能手机
平凡但不平庸的码农17 小时前
Go Slice 详解
算法·golang
炸膛坦客20 小时前
嵌入式 - 数据结构与算法:(1-7)数据结构 - 顺序表和链表的对比
数据结构·链表
Jasmine_llq21 小时前
《B3867 [GESP202309 三级] 小杨的储蓄》
算法·循环遍历·数组累加(模拟)·索引定位·顺序输出
啦啦啦_999921 小时前
案例之 逻辑回归_电信用户流失预测
算法·机器学习·逻辑回归
风筝在晴天搁浅21 小时前
快手/字节 CodeTop LeetCode 415.字符串相加
算法·leetcode
小黄人软件21 小时前
C++读写编辑CSV文件示例源码 用于数据导入导出,比Excel好使
开发语言·c++·excel
郭涤生21 小时前
C++各个版本的性能和安全性总结
开发语言·c++
hoiii1871 天前
基于栅格法的机器人工作空间划分系统
数据结构·机器人
DragonnAi1 天前
猫咪如厕检测与分类识别系统系列【十四】 项目结构重新整理-即将开源完整算法
算法·开源