数组——螺旋矩阵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;
    }
};
相关推荐
aini_lovee几秒前
MATLAB圆锥滚子轴承滚子参数分析程序
人工智能·算法·matlab
_olone5 分钟前
牛客每日一题:显生之宙(Java)
java·开发语言·算法·牛客
嫂子开门我是_我哥19 分钟前
心电域泛化研究从0入门系列 | 第二篇:心电信号预处理全攻略——扫清域泛化建模的第一道障碍
人工智能·算法·ecg
wefg144 分钟前
【算法】算数基本定理、分解质因数
算法
j_xxx404_1 小时前
力扣困难算法精解:串联所有单词的子串与最小覆盖子串
java·开发语言·c++·算法·leetcode·哈希算法
挠头猴子1 小时前
一个数组去重,两个数组找不同或相同
数据结构·算法
big_rabbit05021 小时前
[算法][力扣167]Two Sum II
算法·leetcode·职场和发展
颜酱1 小时前
二分图核心原理与判定算法
javascript·后端·算法
筱砚.2 小时前
C++——lambda
开发语言·c++·算法
Eward-an2 小时前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展