No.191 - LeetCode59. Spiral Matrix II - 經典 - 蛇形數字 - 入門Coding

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<int> dirx,diry;
        dirx = {0,1,0,-1};
        diry = {1,0,-1,0};
        vector<vector<int> > ans(n,vector<int>(n,0));
        int level = n-1;
        int key = 1;
        int locx = 0;
        int locy = 0;
        while(level>0){
            // 枚舉4個方向
            for(int i=0;i<4;i++){
                for(int j=0;j<level;j++){
                    ans[locx][locy] = key++;
                    locx += dirx[i];
                    locy += diry[i];
                }
            }
            level-=2;
            // 向右下移動
            locx ++;
            locy ++;
        }
        if(level == 0)
            ans[locx][locy] = key;
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章