4ms c++ clean solution with explanation


  • 1

    Loop right "++j", down "++i", left "--j", up "--i".
    Only turn under two situations:

    • next step is outside of the matrix

    • next step has been filled

    vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> res(n, vector<int>(n,0));
            if(n==0) return res;
            int k=1, total = n*n, i=0, j=0;
            res[0][0] = 1;
            while(k<total)
            {
                while(j+1<n && res[i][j+1]==0) res[i][++j] = ++k;
                while(i+1<n && res[i+1][j]==0) res[++i][j] = ++k;
                while(j-1>=0 && res[i][j-1]==0) res[i][--j] = ++k;
                while(i-1>=0 && res[i-1][j]==0) res[--i][j] = ++k;
            }
            return res;
        }
    

Log in to reply
 

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