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;

    }
};
相关推荐
电科_银尘几秒前
【大模型算法与工程 52】检索优化:混合召回、重排与查询改写
人工智能·算法·机器学习
猿人谷21 分钟前
Pareto:为什么真正的优化,不是寻找一个最优解?
后端·算法·aigc
cooldream200931 分钟前
计算机专业本科毕业设计系列07——类型④:算法与理论研究
算法·毕业设计·计算机专业·课程设计
劲夫学编程1 小时前
leetcode: 字母异位词分组
算法·leetcode
wy_hhxx1 小时前
[Leetcode] 动态规划(打家劫舍、0-1背包、完全背包)
算法·leetcode·动态规划·完全背包·0-1背包
m0_547486662 小时前
《智能计算》全套课件PDF(武汉工程大学)
算法·贝叶斯算法·智能计算
Shaoshing2 小时前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
weixin_307779132 小时前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
Lazyafei3 小时前
560. 和为 K 的子数组
数据结构·算法
小白的高手之路3 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣