class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n,vector<int>(n,0));
        int num = 1;
        //设定访问边界
        int up = 0,down = n-1,left = 0,right = n -1;
        while(true)
        {
            //从左向右访问
            for(int i = left;i <= right;i++) 
                ans[up][i] = num++;
            if(++up > down) break;
            
            //从上向下访问
            for(int i = up;i <= down;i++)
                ans[i][right] = num++; 
            if(--right < left) break;
            
            //从右向左访问
            for(int i = right;i >= left;i--) 
                ans[down][i] = num++;
            if(--down < up) break;
            
            //从下向上访问
            for(int i = down;i >= up;i--)
                ans[i][left] = num++;
            if(++left > right) break;
        }
        
        return ans;
    }
};

执行结果:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix II.
Memory Usage: 6.6 MB, less than 51.28% of C++ online submissions for Spiral Matrix II.