[Leetcode] Spiral Matrix II

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > res(n, vector<int>(n));
        
        if (n > 0)
        {
            int num = 1;
            
            for (int level = 0; level < n / 2; ++level)
            {
                for (int i = level; i < n - level; ++i)
                    res[level][i] = num++;
                    
                for (int i = level + 1; i < n - level; ++i)
                    res[i][n - level - 1] = num++;
                    
                for (int i = n - level - 2; i >= level; --i)
                    res[n - level - 1][i] = num++;
                    
                for (int i = n - level - 2; i > level; --i)
                    res[i][level] = num++;
            }
            
            if (n % 2 == 1)
                res[n / 2][n / 2] = num;
        }
        
        return res;
    }
};

你可能感兴趣的:([Leetcode] Spiral Matrix II)