My AC of 8 msec solution (c++)


  • 1
    L

    class Solution {
    public:
    vector<vector<int> > generateMatrix(int n) {
    vector<vector<int> >matrix(n, vector<int> (n, 0));

        int num = 1;
        int size = n;
        int depth = 0;
        int total = n*n+1;
        while ( num < total )
        {
            // write the values clock-wise direction.
            for ( int i = 0; i < size; i ++ )
                matrix[depth][depth+i] = num++;
            for ( int i = 1; i < size; i ++ )
                matrix[depth+i][depth+size-1] = num++;
            for ( int i = 1; i < size; i ++ )
                matrix[depth+size-1][depth+size-1-i] = num++;
            for ( int i = 1; i < size-1; i ++ )
                matrix[depth+size-1-i][depth] = num++;
    
            size -= 2;
            depth ++;
        }
    
        return matrix;
    }
    

    };


  • 0
    C

    neat code. judge the boundary by changing direction costs lots of time. your simple neat code is faster.


Log in to reply
 

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