leetcode 链接:螺旋矩阵 II

题目

给你一个正整数 n ,生成一个包含 1n^2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例:
[中等] 59. 螺旋矩阵 II - 图1

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

解答 & 代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result(n, vector<int>(n, 0));
        // 左、右、上、下边界
        int left = 0, right = n - 1, up = 0, down = n - 1;
        int cnt = 1;
        while(left <= right && up <= down)
        {
            for(int col = left; col <= right; ++col, ++cnt)    // 遍历上边界
                result[up][col] = cnt;
            ++up;                                            // 上边界下移
            if(up > down)
                break;

            for(int row = up; row <= down; ++row, ++cnt)    // 遍历右边界
                result[row][right] = cnt;
            --right;                                        // 右边界左移
            if(right < left)
                break;

            for(int col = right; col >= left; --col, ++cnt)    // 遍历下边界
                result[down][col] = cnt;
            --down;                                            // 下边界上移
            if(down < up)
                break;

            for(int row = down; row >= up; --row, ++cnt)    // 遍历左边界
                result[row][left] = cnt;
            ++left;                                            // 左边界右移
            if(left > right)
                break;
        }
        return result;
    }
};

执行结果:

执行结果:通过

执行用时:0 ms, 在所有 C++ 提交中击败了 100.00% 的用户
内存消耗:6.5 MB, 在所有 C++ 提交中击败了 15.24% 的用户