leetcode 59.螺旋矩阵

记录一下,觉得倒水思想来做 总体看起来还是比较清晰的。

bash 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int a[4][2] = {{0,1}, {1,0}, {0,-1},{-1,0}};

        int direction=0;  //方向
        int num=0;

        int S =n*n;
        int x = 0;
        int y = 0;
        
        vector<vector<int>> Matrix(n, vector<int>(n, 0));

        while(num!=S){
            num++;
            Matrix[x][y]=num;

            x+=a[direction][0];
            y+=a[direction][1];
            if(x>=n || y>=n || x<0 || y<0 || Matrix[x][y]!=0){
                x-=a[direction][0];
                y-=a[direction][1];
                direction = (direction+1)%4;
                x+=a[direction][0];
                y+=a[direction][1];
            } 
        }  
        return  Matrix;

    }
};
相关推荐
椰羊~王小美1 小时前
LeetCode -- Flora -- edit 2025-04-27
算法·leetcode·职场和发展
18538162800余--2 小时前
矩阵系统源码搭建热门音乐功能板块开发,支持OEM
线性代数·矩阵
缘友一世2 小时前
从线性回归到逻辑回归
算法·逻辑回归·线性回归
前端_学习之路3 小时前
javaScript--数据结构和算法
javascript·数据结构·算法
weixin_428498493 小时前
使用HYPRE库并行装配IJ稀疏矩阵指南: 矩阵预分配和重复利用
算法·矩阵
雾削木5 小时前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
__lost5 小时前
小球在摆线上下落的物理过程MATLAB代码
开发语言·算法·matlab
mit6.8247 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表
巷北夜未央7 小时前
空间矩阵的思考
线性代数·矩阵
jerry6098 小时前
优先队列、堆笔记(算法第四版)
java·笔记·算法