4ms C++ solution, easy to understand


  • 2
    H
    class Solution {
    public:
     vector< vector<int> > generateMatrix(int n) {
        vector< vector<int> > vvi;
        if(n==0) return vvi;
        int up = 0, right = n-1, bottom = n-1, left = 0;
        for(int i = 0; i<n; i++) vvi.push_back(vector<int>(n));
        int i = 1, j;
        while(i<=n*n){
            for(j = left; i<=n*n&&j<=right; i++, j++) vvi[up][j] = i;
            up++;
            for(j = up; i<=n*n&&j<=bottom; i++, j++) vvi[j][right] = i;
            right--;
            for(j = right; i<=n*n&&j>=left; i++, j--) vvi[bottom][j] = i;
            bottom--;
            for(j = bottom; i<=n*n&&j>=up; i++, j--) vvi[j][left] = i;
            left++;
        }
        return vvi;
    }
    };

Log in to reply
 

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