Short c++ 4ms solution


  • 0
    P
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> mat(n,vector<int>(n,0));
            if(n==0) return mat;
            for(int k=1,i=0,j=0;k<=n*n;k++){
                mat[i][j] = k;
                if(i<(n+1)/2 && i<=j+1 && i<n-j-1) j++;
                else if(j>=n/2 && n-j-1<=i && n-j-1<n-i-1) i++;
                else if(i>=(n+1)/2 && n-i-1<=n-j-1 && n-i-1<j) j--;
                else i--;
            }
            return mat;
        }
    };

Log in to reply
 

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