数组——螺旋矩阵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;
    }
};
相关推荐
.鱼子酱18 分钟前
机器学习 - 使用 ID3 算法从原理到实际举例理解决策树
算法·决策树·机器学习
微露清风29 分钟前
系统性学习数据结构-第三讲-栈和队列
java·数据结构·学习
Swift社区1 小时前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区1 小时前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
ajassi20001 小时前
开源 C++ QT Widget 开发(十三)IPC通讯--本地套接字 (Local Socket)
linux·c++·qt·开源
Q741_1471 小时前
C++ 前缀和 高频笔试考点 实用技巧 牛客 DP34 [模板] 前缀和 题解 每日一题
开发语言·c++·算法·前缀和·牛客网
YaoYuan93231 小时前
C++ 容器——unordered_xxx
c++
凤年徐2 小时前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象
lifallen2 小时前
Kafka 内存池MemoryPool 设计
数据结构·kafka·apache
RTC老炮2 小时前
webrtc弱网-LossBasedBandwidthEstimation类源码分析与算法原理
网络·算法·webrtc