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;

    }
};
相关推荐
Nil20819 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
wanderist.21 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.21 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_3077791321 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂1 天前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
光影少年1 天前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
HEJOO91 天前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
Code_Solitude1 天前
c语言:递归
java·c语言·算法
edtoplort1 天前
OpenAI紧急叫停GPT-6.1 Astra训练,奥尔特曼为何踩刹车
人工智能·gpt·算法
蒜香可达鸭1 天前
让视频生成流水线跑不崩:一个事件溯源的多 Agent 可靠执行框架
算法