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;

    }
};
相关推荐
NEFU_Jyj2 小时前
牛客周赛R168
算法
文丑颜不良啊9 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z10 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH10 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶11 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊11 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊12 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
文丑颜不良啊13 小时前
LeetCode2141~2160题目解析
java·leetcode
LabVIEW开发13 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview