当前位置: 首页 > news >正文

leetcode数组-螺旋矩阵Ⅱ

题目

题目链接:https://leetcode.cn/problems/spiral-matrix-ii/

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

思路 & 代码
  • 每条边的循环规则:左闭右开
    • 每条边只遍历到倒数第二个节点,最后一个节点留给下一条边处理;

image.png

#include <vector>
#include <iostream>
using namespace std;

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int startx = 0, starty = 0;
        int offset = 1;
        int count = 1;
        int i,j;
        int loop = n/2;
        vector<vector<int>> res(n,vector<int>(n));
        while(loop--){
            i = startx;
            j = starty;
            for(j; j < n - offset; j++){
                res[i][j] = count++;
            }
            for(i; 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) {
            res[n/2][n/2] = count;
        }
        return res;
    }
};
// @lc code=end

void printVector(vector<vector<int>>& nums){
    cout << "[";
    for(int i = 0; i < nums.size(); i++){
        if(i != 0) cout << " ";// 子数组之间加空格分隔
        cout << "[";
        for(int j = 0; j < nums[i].size(); j++){
            cout << nums[i][j];
            if(j != nums[i].size() - 1) cout << ", ";//每行的最后一个元素不加逗号
        }
        cout << "]";
        if(i != nums.size() - 1) cout << ",";// 最后一个子数组不加逗号
    }
    cout << "]" << endl;
}

int main() {
    Solution obj;
    int n = 3;
    vector<vector<int>> res = obj.generateMatrix(n);
    
    printVector(res);
    
}

相关文章:

  • NSSCTF [FSCTF 2023]Fi3h
  • Python语言的测试用例设计
  • 【C#深度学习之路】如何使用C#实现Stable Diffusion的文生图功能
  • Linux文件特殊权限管理及进程和线程
  • Roo Code(前身为 Roo Cline)一个 AI 驱动的自主编码代理
  • C++stl map容器详解
  • openHalo:国产开源数据库新力量
  • HCIP【BGP协议(详解)】
  • 搜索与图论 树的深度优先遍历 树的重心
  • Windows 权限配置文件解析与安全分析(GPP,GPO,LSA)
  • 查询当前用户的购物车和清空购物车
  • 57.基于springboot和vue校园跑腿服务平台
  • CSS语言的硬件驱动
  • 第五讲(上) | string类的使用
  • Linux | 安装超级终端串口软件连接i.MX6ULL开发板(8)
  • Git 从入门到精通(开源协作特别版)
  • Windows安装Node.js+Express+Nodemon
  • 6.1 宽度优先搜索算法(BFS)
  • 1.Qt信号与槽
  • 如何删除Debian中的用户?删除Debian用户方法
  • 铜陵建设行业培训学校网站/百度打车客服电话
  • 网站怎么做收入/百度快照怎么发布
  • 怎么建设宣传网站/中国站长
  • 网站设计的公司蒙特/腾讯广告代理商加盟
  • 毕业设计拼车网站的建设雨实现/做网页设计的软件
  • 正能量网站建设/杭州搜索推广公司