My 7ms solution, easy to understand (I hope)


  • 0
    P

    Here is it:

    class Solution {
    public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > v(n);
        for (int i=0; i<n; ++i)
            v[i].resize(n);
        
        int xi=0, yi=0, circ=0;
        for (int i=1; i<=n*n; ++i)
        {
            v[yi][xi] = i;
            if (yi==circ)
            {
                if (xi<n-circ-1)
                    ++xi;
                else
                    ++yi;
            }
            else
            if (xi==n-circ-1)
            {
                if (yi<n-circ-1)
                    ++yi;
                else
                    --xi;
            }
            else
            if (yi==n-circ-1)
            {
                if (xi>circ)
                    --xi;
                else
                    --yi;
            }
            else
            {
                if (yi>circ+1)
                    --yi;
                else
                {
                    ++xi;
                    ++circ;
                }
            }
        }
        return v;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.