LeetCode59 Spiral Matrix II 螺旋矩阵 II

问题描述:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题源:here;完整实现:here
思路:
方法同第54题,我们一层一层的构造螺旋矩阵,代码如下:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result(n, vector<int>(n));
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        int count = 1;
        while (left <= right){
            for (int i = left; i <= right; i++) result[top][i] = count++;
            if (left < right){
                for (int i = top + 1; i < bottom; i++) result[i][right] = count++;
                for (int i = right; i > left; i--) result[bottom][i] = count++;
                for (int i = bottom; i > top; i--) result[i][left] = count++;
            }
            left++; right--; top++; bottom--;
        }

        return result;
    }
};

你可能感兴趣的:(LeetCode实践)