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;

    }
};
相关推荐
And_Ii8 小时前
LeetCode 3397. 执行操作后不同元素的最大数量
数据结构·算法·leetcode
额呃呃8 小时前
leetCode第33题
数据结构·算法·leetcode
隐语SecretFlow8 小时前
【隐语SecretFlow用户案例】亚信科技构建统一隐私计算框架探索实践
科技·算法·安全·隐私计算·隐私求交·开源隐私计算
dragoooon348 小时前
[优选算法专题四.前缀和——NO.27 寻找数组的中心下标]
数据结构·算法·leetcode
少许极端9 小时前
算法奇妙屋(七)-字符串操作
java·开发语言·数据结构·算法·字符串操作
小龙报9 小时前
《算法通关指南---C++编程篇(2)》
c语言·开发语言·数据结构·c++·程序人生·算法·学习方法
金宗汉9 小时前
《宇宙递归拓扑学:基于自指性与拓扑流形的无限逼近模型》
大数据·人工智能·笔记·算法·观察者模式
豆沙沙包?9 小时前
2025年--Lc201- 378. 有序矩阵中第 K 小的元素(排序)--Java版
java·线性代数·矩阵
YY_TJJ11 小时前
算法题——贪心算法
算法·贪心算法
C++ 老炮儿的技术栈11 小时前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio