LeetCode59 螺旋矩阵II 2018.4.29

题干:

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

示例:

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

跟前面有一题非常像,ac代码如下

class Solution {
    public:
    vector<vector<int>> generateMatrix(int n)
    {
        vector<vector<int>>result(n,vector<int>(n,0));
        int num = 1;
        int sum = n * n;
        int x = 0,y = 0;
        while(num <= sum)
        {
            while(y < n && result[x][y] == 0)//向右
                result[x][y++] = num++;
            x++,y--;//向下移一位,y已经变成了n
            while(x < n && result[x][y] == 0)//向下
                result[x++][y] = num++;
            y--,x--;
            while(y >= 0 && result[x][y] == 0)//向左
                result[x][y--] = num++;
            x--,y++;
            while(x >= 0 && result[x][y] == 0)//向上
                result[x--][y] = num++;
            y++,x++;
            n--;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/jerseywwwwei/article/details/80141334
今日推荐