[leetcode][59. 螺旋矩阵 II]

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解答:

菜鸟解法

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result;
        if (n==1) {result.push_back(vector<int>(1,1));return result;}
        for(int i=0;i<n;i++)
            result.push_back(vector<int>(n,0));
        int count=0,x=0,y=0;
        int num=n*n;
        while(true)
        {
            while(y<n&&result[x][y]==0){result[x][y]=++count;y++;}
            if(count==num) break;
            --y;
            ++x;
            
            while(x<n&&result[x][y]==0){result[x][y]=++count;x++;}
            if(count==num) break;
            --x;
            --y;
            
            while(y>=0&&result[x][y]==0){result[x][y]=++count;y--;}
            if(count==num) break;
            ++y;
            --x;
            
            while(x>=0&&result[x][y]==0){result[x][y]=++count;x--;}
            if(count==num) break;
            ++x;
            ++y;
            
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/Linger0519/article/details/82598479